C# Clear richTextBox in Timer - c#

I want to save richTextBox.Text every minute, when user checked save checkbox.
here checkbox event.
num_saveTime is numericUpDown control for inpute minute.
save_timer is global variable.
private void chk_save_CheckedChanged(object sender, EventArgs e)
{
if (chk_save.Checked)
{
num_saveTime.Enabled = false;
save_timer = new System.Timers.Timer();
save_timer.Elapsed += new System.Timers.ElapsedEventHandler(save_timer_Elapsed);
save_timer.Interval = 250;
save_timer.Start();
}
else
{
num_saveTime.Enabled = true;
save_timer.Stop();
}
}
and Timer Event
delegate void TimerDelegate(object sender, System.Timers.ElapsedEventArgs e);
void save_timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (rtxb_PKT.InvokeRequired)
{
TimerDelegate tdel = new TimerDelegate(save_timer_Elapsed);
rtxb_PKT.Invoke(tdel, new object[] { sender, e });
}
else
{
string now_ss = DateTime.Now.ToString("ss");
if (now_ss.Equals("00"))
{
string now_mm = DateTime.Now.ToString("mm");
string save_mm = Convert.ToInt32(num_saveTime.Value).ToString("D2");
if (save_mm.Equals(now_mm))
{
string path = Application.StartupPath + #"\" + DateTime.Now.ToString("yy-MM-dd--HH-mm-sss") + ".rtf";
rtxb_PKT.SaveFile(path, RichTextBoxStreamType.RichText);
rtxb_PKT.Clear(); //----here
}
}
}
}
I want clear richTextBox after save.
But I insert .Clear() that position, it clear text before save, so file is empty...
How can I clear it after saving?

Related

How to update the text in a listView with the DownloadFileAsync progress percentage?

I am currently making a podcast client to download episodes. I have got a listView filled with the episodes for a feed and then when you double click on one it places it into a separate 'downloads' lisview which has a 'name' and a 'progress' column.
The problem I am having is trying to individually update each progress while downloading asynchronously. As I am not sure of how to keep track of the progress for each ListViewItem and how to reference it in the downloadProgressChanged function.
private void lvPodDownloads_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lvPodEpisodes.SelectedItems.Count == 1) // Check if an item is selected just to be safe
{
ListViewItem item = (ListViewItem)lvPodEpisodes.SelectedItem;
string[] epInfo = (string[])item.Tag;
txtTitle.Text = epInfo[0];
txtDesc.Text = epInfo[1];
try
{
imgFeedImage.Source = new BitmapImage(new Uri((Environment.CurrentDirectory + "\\..\\..\\feedImages\\" + epInfo[3])));
}
catch (Exception) // If it fails to set the image (Eg. It's non-existent) It will leave it blank
{
imgFeedImage.Source = null;
}
}
}
private void lvPodEpisodes_MouseDoubleClick(object sender, MouseButtonEventArgs e) // Downloading the episode in here
{
if (e.ChangedButton == MouseButton.Left) // Left button was double clicked
{
ListViewItem selected = (ListViewItem)lvPodEpisodes.SelectedItem;
string[] epInfo = (string[])selected.Tag;
Uri downloadUrl = new Uri(epInfo[2]);
List<Episode> downloading = new List<Episode>();
downloading.Add(new Episode() { Title = epInfo[0], Progress = "0%" });
lvPodDownloads.Items.Add((new Episode() { Title = epInfo[0], Progress = "0%" }));
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
}
}
}
static int intDownloadProgress = new int();
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
intDownloadProgress = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}
This is a code sample of the downloading section of the program.
Here is an image of what I have so far:
https://s33.postimg.cc/gthzioxlr/image.png
You should add an extra argument to your ProgressChanged method.
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Episode curEpisode)
{
curEpisode.Progress = $"{e.ProgressPercentage} %";
}
And to modify the handler setting like that:
List<Episode> downloading = new List<Episode>();
var newEpisode = new Episode() { Title = epInfo[0], Progress = "0%" };
downloading.Add(newEpisode);
lvPodDownloads.Items.Add(newEpisode);
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, newEpisode));
}
The static property intDownloadProgress is then useless.
You should also think about using an observable collection for the episode list and using it for the binding via the XAML code.

ShowDialogue not generating DialogueResult.OK

I'm writing a program that's supposed to download something off GitHub. It has a link to a raw file on GitHub. I'm using DownloadDataAsync to download it, and I have a progress bar to track how far it is in the download. It always gets to 100%, but then it does nothing.
I've been following a tutorial for a C# updater by BetterCoder (The beginning starts here and the most relevant part would be Part 9 of the series).
This is the part where it stops working properly:
private void DownloadUpdate(SaveyourUpdateXML update)
{
SharpUpdateDownloadForm form = new SharpUpdateDownloadForm(update.Uri, update.MD5, this.applicationInfo.ApplicationIcon);
Debug.WriteLine("form created");
DialogResult result = form.ShowDialog(this.applicationInfo.Context);
Debug.WriteLine("got result");
if (result == DialogResult.OK)
{
String currentPath = this.applicationInfo.ApplicationAssembly.Location;
String newPath = Path.GetDirectoryName(currentPath) + "\\" + update.FileName;
UpdateApplication(form.TempFilePath, currentPath, newPath, update.LaunchArgs);
Application.Exit();
}
}
It never gets to the "got result" part unless I cancel it. Also, this.applicationInfo.Context returns a form. However, it does say "form created".
I think there's something wrong with the way ShowDialog is used or something, but I'm not really sure what.
Edit: This is what happens when a SharpUpdateDownloadForm is created.
internal SharpUpdateDownloadForm(Uri location, String md5, Icon programIcon)
{
InitializeComponent();
if (programIcon != null)
{
this.Icon = programIcon;
}
tempFile = Path.GetTempFileName();
this.md5 = md5;
webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
try
{
webClient.DownloadDataAsync(location, this.tempFile);
}
catch
{
this.DialogResult = DialogResult.No;
this.Close();
}
}
This is what should happen when a download is completed:
private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
this.DialogResult = DialogResult.No;
this.Close();
}
else if (e.Cancelled)
{
this.DialogResult = DialogResult.Abort;
this.Close();
}
else
{
lblProgress.Text = "Verifying Download...";
progressBar.Style = ProgressBarStyle.Marquee;
bgWorker.RunWorkerAsync(new string[] {this.tempFile, this.md5});
}
}
This is bgWorker_RunWorkerCompleted
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.DialogResult = (DialogResult)e.Result;
this.Close();
}
And bgWorker_DoWork
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
String file = ((string[])e.Argument)[0];
String updateMD5 = ((string[])e.Argument)[1];
if (Hasher.HashFile(file, HashType.MD5) != updateMD5)
e.Result = DialogResult.No;
else
e.Result = DialogResult.OK;
}
When webClient.DownloadDataAsync completes, it fires DownloadDataCompleted event, not DownloadFileCompleted - the one you registered.
The fix is, if you use webClient.DownloadDataAsync, register the DownloadDataCompleted event; Note that the 2nd argument to webClient_DownloadDataCompleted is different.
webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(webClient_DownloadDataCompleted);
...
private void webClient_DownloadDataCompleted(Object sender, DownloadDataCompletedEventArgs e)
{
...
}

How to make one event to identify whether multiple radio buttons are checked?

I have the following code which checks each radio button (Temp30, Temp40 and Temp60) and does the necessary things such as turning the wash temperature light on etc...
I want to create an event which handles all 3 radio buttons. I thought it could possibly have something to do with the groupbox they are in? (it is called TempGroupBox)
Any help would be much appreciated!
private void Temp30_CheckedChanged(object sender, EventArgs e)
{
if (Temp30.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._30degrees;
SpeedGroupBox.Enabled = true;
}
}
private void Temp40_CheckedChanged(object sender, EventArgs e)
{
if (Temp40.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._40degrees;
SpeedGroupBox.Enabled = true;
}
}
private void Temp60_CheckedChanged(object sender, EventArgs e)
{
if (Temp60.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._60degrees;
SpeedGroupBox.Enabled = true;
}
}
You can bind all radioButton's event to the same handler and use sender parameter to get the control that the action is for.
private void Temps_CheckedChanged(object sender, EventArgs e)
{
string checkedName = ((RadioButton)sender).Name;
if(checkedName == "Temp40")
{
...
}
else if(checkedName == "Temp60")
{
...
}
}
You can add event handler for all RadioBUttons's like that after InitializeComponent():
var radioButtons =this.Controls.OfType<RadioButton>();
foreach (RadioButton item in radioButtons)
{
item.CheckedChanged += Temps_CheckedChanged;
}

ADD url in textbox to listbox in Windows Form Application c#

Iam new in programming.In windows Form application ,I want user can write a url in textbox and add (with button) in listbox as a favorite list,then user can click in listbox and then go to browser, finaly can save and open the list? whitout Microsoft Sql Database.I Need a source code.
textbox: (Enter your WebSite) : www.google.com
Button:ADD To List Box
Listbox:WWW.Google.com
Button :Save
Button :Open
You have to save the ListBox.Items as plain text file if not wanting to use database. Without binding, this simple problem becomes a little nasty if you start digging into writing it. Here is one of the solution you may need:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int lastIndex = -1;
bool suppressSelectedIndexChanged;
//Click event handler for buttonAdd
private void buttonAdd_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
suppressSelectedIndexChanged = true;
listBox1.SelectedIndex = listBox1.Items.Count - 1;
suppressSelectedIndexChanged = false;
}
//Click event handler for buttonRemove
private void buttonRemove_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndices.Count == 0) return;
int k = listBox1.SelectedIndices[0];
suppressSelectedIndexChanged = true;
for (int i = listBox1.SelectedIndices.Count - 1; i >= 0; i--)
listBox1.Items.RemoveAt(listBox1.SelectedIndices[i]);
suppressSelectedIndexChanged = false;
lastIndex = -1;
listBox1.SelectedIndex = k < listBox1.Items.Count ? k : listBox1.Items.Count - 1;
if (listBox1.Items.Count == 0) textBox1.Clear();
}
//Click event handler for buttonSave
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "URLs file|*.urls";
save.FileOk += (s, ev) =>
{
using (StreamWriter writer = File.CreateText(save.FileName))
{
foreach (object item in listBox1.Items)
{
writer.WriteLine(item.ToString());
}
}
};
save.ShowDialog();
}
//Click event handler for buttonOpen
private void buttonOpen_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "URLs file|*.urls";
open.FileOk += (s, ev) =>
{
listBox1.Items.Clear();
using (StreamReader reader = File.OpenText(open.FileName))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
};
open.ShowDialog();
}
//SelectedIndexChanged event handler for listBox1
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (suppressSelectedIndexChanged) return;
if (lastIndex > -1)
{
listBox1.Items[lastIndex] = textBox1.Text;
}
lastIndex = listBox1.SelectedIndex;
if (listBox1.SelectedIndex > -1)
textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
}
//Click event handler for buttonVisit
private void buttonVisit_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem == null) return;
System.Diagnostics.Process.Start(listBox1.SelectedItem.ToString());
}
}
Here is the GUI screen shot for you to know which controls are needed:
private void btnAdd_Click(object sender, EventArgs e)
{
string _webstring = #"http://";
string _website = _webstring + textBox1.Text;
listBox1.Items.Add(_website);
using (StreamWriter w = File.AppendText("websites.txt"))
{
WriteLog(_website, w);
}
using (StreamReader r = File.OpenText("websites.txt"))
{
DisposeLog(r);
}
}
private void btnLaunch_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("iexplore.exe", listBox1.SelectedItem.ToString());
}
private void btnSave_Click(object sender, EventArgs e)
{
using (StreamWriter w = File.AppendText("websites.txt"))
{
foreach (string items in listBox1.Items)
{
WriteLog(items, w);
}
}
using (StreamReader r = File.OpenText("websites.txt"))
{
DisposeLog(r);
}
}
public static void WriteLog(string logMessage, TextWriter w)
{
w.WriteLine(logMessage, logMessage);
}
public static void DisposeLog(StreamReader r)
{
string line;
while ((line = r.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
private void btnRetrieve_Click(object sender, EventArgs e)
{
using (TextReader txtRead = File.OpenText("Websites.txt"))
{
string _text = "";
string[] _textArray = null;
while ((_text = txtRead.ReadLine()) != null)
{
_textArray = _text.Split('\t');
listBox1.Items.Add(txtRead.ReadLine());
}
txtRead.Close();
}
}
hope this helps.. thanks

Setting a timer to an event

I intend to put a timer in my the following code so that that the button will be enabled again after 5 seconds. AS you can see, my send button will be disabled after the user send 5 message. I want to enabled it after 5 seconds have elapsed.
Any suggestion is welcomed.
public bool stopSpam(int counter)
{
int spam = counter;
if (spam < 6)
{
return false;
}
else
{
return true;
}
}
private void button1_Click(object sender, EventArgs e)
{
counter++;
bool check = stopSpam(counter);
if (check == false)
{
if (textBox2.Text != "")
{
if (textBox2.Text.ToLower().StartsWith("/"))
{
onCommand(textBox2.Text);
string datetimestring = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}.txt", DateTime.Now);
String exePath = string.Format(Application.StartupPath + "\\logs\\" + "msglogs {0}", datetimestring);
StreamWriter writer = File.CreateText(exePath);
writer.Write(textBox1.Text);
writer.Close();
textBox2.Text = "";
}
else
{
m_ChildConnection.SendMessage("MSG :" + textBox2.Text);
string datetimestring = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}.txt", DateTime.Now);
String exePath = string.Format(Application.StartupPath + "\\logs\\" + "msglogs {0}", datetimestring);
StreamWriter writer = File.CreateText(exePath);
writer.Write(textBox1.Text);
writer.Close();
textBox2.Text = "";
}
}
}
else
{
button1.Enabled = false;
}
Thanks in adavence!
Have a timer, set its interval to 5 seconds (5000). Keep it disabled by default.
When the button is pressed enable the timer
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
timer.Enabled = true;
}
When a tick occurs after 5 seconds, enable the button and disable the timer again.
private void timer_Tick(object sender, EventArgs e)
{
button1.Enabled = true;
timer.Enabled = false;
}
Hard to figure out what you're trying to achieve but you could take the following steps to disable the enable the button after 5 seconds.
Add:
private Timer t;
as a class variable.
then after your InitializeComponent add:
t = new Timer(5000){Enabled = false, Tick += (myTick)};
then add this method:
private void myTick(object source, ElapsedEventArgs e)
{
button1.Enabled = true;
}
Also, consider updating this method:
your stopSpam method to:
public bool stopSpam(int counter)
{
return counter >= 6;
}
In fact, there is actually no need for the method:
Simply change
if(check == false)
to
if(counter > 5)
You can simply use System.Timers.Timer class to put timer.
//Define the timer
private System.Timers.Timer buttonTimer;
// Initialize the timer with a five second interval.
buttonTimer= new System.Timers.Timer(5000);
// Hook up the Elapsed event for the timer.
buttonTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
//Start the timer
buttonTimer.Start();
// Enable the button in timer elapsed event handler
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
button1.Enabled = true;
}

Categories

Resources