I have the following piece of code:
class NotepadCloneNoMenu : Form
{
protected TextBox txtbox;
public NotepadCloneNoMenu(string a)
{
Text = "Notepad Clone No Menu";
txtbox = new TextBox();
txtbox.Parent = this;
txtbox.Dock = DockStyle.Fill;
txtbox.BorderStyle = BorderStyle.None;
txtbox.Multiline = true;
txtbox.ScrollBars = ScrollBars.Both;
txtbox.AcceptsTab = true;
txtbox.AppendText(a);
txtbox.AppendText("\n");
}
}
class program1
{
public static void Main()
{
string result = "abc";
while(true)
{
Application.Run(new NotepadCloneNoMenu(result));
}
}
}
I want to continuously appending the string result to the textbox so it looks like this:
abc
abc
abc
so on and so forth. However, every time I called this:
Application.Run(new NotepadCloneNoMenu(result));
It will reset the textbox. Is there anyway I can update the textbox continuously? I am fairly new to C# so this is quite confusing to me.
thanks,
Phuc Pham
First of all, you're continuously closing and opening an application. That's why it resets. If you want to run an infinite loop, you probably want to run it inside your application proper.
In your application code, use some event (maybe a timer would suit you) to append text to the textBox. Like this:
public someEventOnTheForm (object sender, EventArgs e)
{
txtBox.Text += "Notepad Clone to Menu";
}
There's two more things to take into account: first, if you don't have a stoping condition, this will just keep filling memory until you run out of it.
Second, windows forms run on only one thread by default. You'll be using that thread to update the textbox, so while it's appending text, the form itself will be unusable. It'll probably blank out during the event if it starts taking long. You'll need a second thread to handle the event if you want your form to be usable.
Related
I am creating an application that involves using threads. Everything works until I click the button for the second time. Nothing happens on the second time the button is clicked. Its like the first time all the stuff loads and then just locks the values of the text boxes. The stuff in red is just private links that cannot be shown. Its not the links because they work just fine the first time. They just won't work the second time. I hope what I just said wasn't too confusing.
name1, name2, name3 are all downloaded when the form is created, they're just bound to the textboxes when you press the button the first time.
_name1(), _name2(), _name3() methods are just object instantiations and have no side effects of any kind (put differently, they don't do anything).
And all the threading stuff is just fluff - you're calling methods that don't do anything and then aborting the threads (thereby aborting something that isn't doing anything anyway). This has zero effect on the execution in any way as the code is currently written, even when executed the first time.
The simple, synchronous fix for your code will look like this:
private void Button_Click(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
textBox1.Text = client.DownloadString("<your URL here>");
textBox2.Text = client.DownloadString("<your URL here>");
textBox3.Text = client.DownloadString("<your URL here>");
}
}
Seeing as you're using threads, your goal is obviously non-blocking, asynchronous execution. The easiest way to achieve it while preserving the sequencing of operations is with async/await:
private async void Button_Click(object sender, EventArgs e)
{
// Disabling the button ensures that it's not pressed
// again while the first request is still in flight.
materialRaisedButton1.Enabled = false;
try
{
using (WebClient client = new WebClient())
{
// Execute async downloads in parallel:
Task<string>[] parallelDownloads = new[] {
client.DownloadStringTaskAsync("<your URL here>"),
client.DownloadStringTaskAsync("<your URL here>"),
client.DownloadStringTaskAsync("<your URL here>")
};
// Collect results.
string[] results = await Task.WhenAll(parallelDownloads);
// Update all textboxes at the same time.
textBox1.Text = results[0];
textBox2.Text = results[1];
textBox3.Text = results[2];
}
}
finally
{
materialRaisedButton1.Enabled = true;
}
}
What I am doing:
I am receiving a string of data every second constantly from a serial port. I am processing it and also displaying this string on the rich text box.
Problem:
I want the user to go through the old strings and copy any, but user can't do it because data is coming every second and auto-scrolling occurs.
My desired solution:
I am thinking to have a check-box 'pause'. when user checks it updating of rich text box stops. and user can go in history and copy a string. but in the mean while I don't want to stop the incoming strings from the serial port as I am doing other things as well with the incoming strings.
So when user uncheck 'pause' checkbox, all the strings which had arrived earlier while user had checked' pause' checkbox also appear on rich text box along with new ones.
is there a way to do it ?
Suppose that when you check the Pause button then every incoming text is appended to a StringBuilder instead of the RichTextBox. When the user uncheck the Pause button you copy everything from the StringBuilder to the RichTextBox
// Assume that these are somewhere globals of your forms
RichTextBox rtb = new RichTextBox();
CheckBox chkPause = new CheckBox();
StringBuilder sb = new StringBuilder();
protected void chkPause_CheckedChanged(object sender, EventArgs e)
{
if(!chkPause.Checked)
{
rtb.AppendText = sb.ToString();
// Do not forget to clear the buffer to avoid errors
// if the user repeats the stop/go cycle.
sb.Clear();
}
else
{
// Start a timer to resume normal flow after a timer elapses.
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = GetSuspensionMilliseconds();
t.Tick += onTick;
t.Start();
}
}
protected void onTick(object sender, EventArgs e)
{
if (chkPause.Checked)
{
// Set to false when the timing elapses thus triggering the CheckedChanged event
chkPause.Checked = false;
System.Windows.Forms.Timer t = sender as System.Windows.Forms.Timer;
t.Stop();
}
}
now in the point where the incoming data is passed to the RichTextBox you could add
....
string incomingData = ReceiveDataFromSerialPort();
if(chkPause.Checked)
sb.AppendLine(incomingData);
else
rtb.AppendText = incomingData;
So, I'm trying to develop a simple application in visual C# which gets data from serial port and displays it in a textbox (to monitor temperature). I'm acquiring and displaying the data successfully, using the DataReceived event to update a global string variable and a timer to update the text field on my text box, as shown:
private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
try
{
globalVar.updateTemp = port.ReadLine(); //This is my global string
}
catch (IOException)
{
}
catch (InvalidOperationException)
{
}
catch (TimeoutException)
{
}
}
private void timer1_Tick(object sender, EventArgs e)
{
tempDisplayBox.Text = globalVar.updateTemp; //This is my textbox updating
}
The only issue I have is that the value shown in the textbox keeps flashing, making it hard to read. My timer is set to trigger every 10 ms (which should be fast enough, right?). Is there any way to make it more stable? I realize this may be a newb question, but to be fair I am a newb :) Any help is appreciated! Thanks!
Do you really need it updating every 10ms? What about every 500 ms or if not that then 100ms. 100ms will require your update method run 10 times less and therefore update 10 times less. The flickering you are expiriencing is due to the refresh speed. You could create custom method which will only update the temp only when target Label or textBox value is different than source port. But that will only sort the flickering when temp is steady, when temp will start vary it will bring back the flickering. Good luck ;-)
UPDATE
Hi I tried to reproduce the conditions and could not make my textbox nor Label flash. The way I tested it was by assigning int ntick = 0; and then increment the ++ntick; inside of the timer_tick method. The results didn't make any of the controls flash and were updated even every milisecond at some point. I also tried string.Format to put some load on the method. Is your app responsive?
The trick is to use double buffering. This way the operating system will redraw the Control off-screen, and only show the control when it is fully redrawn.
I have had the same problem, and solved it by extending the TextBox control like this:
public FastLogBox()
{
InitializeComponent();
_logBoxText = new StringBuilder(150000);
timer1.Interval = 20;
timer1.Tick += timer1_Tick;
timer1.Start();
SetStyle(ControlStyles.DoubleBuffer, true);
}
void timer1_Tick(object sender, EventArgs e)
{
if (_timeToClear)
{
_logBoxText.Clear();
_timeToClear = false;
}
if (_logQueue.Count <= 0) return;
while (!_logQueue.IsEmpty)
{
string element;
if (!_logQueue.TryDequeue(out element)) continue;
{
_logBoxText.Insert(0, element + "\r\n");
}
}
if (_logBoxText.Length > 150000)
{
_logBoxText.Remove(150000, _logBoxText.Length - 150001);
}
Text = _logBoxText.ToString();
}
public new void Clear()
{
_timeToClear = true;
while (!_logQueue.IsEmpty)
{
string element;
_logQueue.TryDequeue(out element);
}
}
public void AddToQueue(string message)
{
_logQueue.Enqueue(message);
}
}
I also use a timer and a concurrentQueue to avoid using Invoke to update the control from another thread. I also use a StringBuilder to prepare the string before putting it into the TextBox. StringBuilder is faster when building larger strings.
You can use ReadExisting() to read the whole data at a time.
You need to handle DataReceived Event of SerialPort
serialPort1.ReadExisting();
Sample:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
String myData=serialPort1.ReadExisting();
}
Example Code: Here i would like to show you the code to Read Data(RFID Tag Code which is basically of length 12)
String macid = "";
private void DoWork()
{
Invoke(
new SetTextDeleg(machineExe ),
new object[] { macid });
macid = "";
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string str1;
macid += serialPort1.ReadExisting();
if (macid.Length == 12)
{
macid = macid.Substring(0, 10);
Thread t = new Thread(new ThreadStart(DoWork));
t.Start();
}
}
public void machineExe(string text)
{
TextBox1.Text=text;
}
Thank you so much for the answers! I found a way to work around this issue:
Instead of replacing the contents of my textbox by rewriting the TextBox.Text property - which, as HenningNT implied, refreshes the control and causes the flickering - I'm now using the TextBox.AppendText method. Though, as I want to display only one line of data at a time, I use the textbox in multiline mode and the Environment.NewLine to jump to a new line before appending the text. As for the method of updating, I've gone back to using the timer because with the invoke method was crashing my application when I close the form, for some reason. Also, enabling double buffering didn't do me much good, although I guess I was doing it wrong... It still flickers a bit, but it's much better now :) I know this is not really a perfect solution (much more of a workaround), so I'll keep looking for it. If I find it, I'll be sure to update it here ;) My code:
private void timer1_Tick(object sender, EventArgs e) //Timer to update textbox
{
if (tempDisplayBox.Text != globalVar.updateTemp) //Only update if temperature is different
{
try
{
tempDisplayBox.AppendText(Environment.NewLine);
tempDisplayBox.AppendText(globalVar.updateTemp);
}
catch (NullReferenceException)
{
}
}
}
This is what I did in MainPage.xaml.cs to create the text animation effect:
private readonly double TEXT_TIMER = 30.0;
private int index;
private void updateText(String text)
{
_text = text;
index = 0;
MainTextBlock.Text = "";
_textTimer.Tick += _textTimer_Tick;
_textTimer.Interval = TimeSpan.FromMilliseconds(TEXT_TIMER);
_textTimer.Start();
}
private void _textTimer_Tick(object sender, EventArgs e)
{
if (index < _text.Length)
{
string s = _text[index].ToString();
MainTextBlock.Text += s;
index++;
}
else
{
_textTimer.Stop();
}
}
I have a list of texts/strings and also a button, say NextButton on the MainPage.xaml. The updateText method is in the click event of NextButton, and what it does is to fetch a text from the list of texts/strings and update the textblock using the animation effect.
But I realised that as I continued to click on the NextButton, it was as if the value of TEXT_TIMER was reducing and the animation effect happened more rapidly until there was no animation anymore (i.e. the text just appeared in the textblock without any effects).
Anybody got any idea why this is happening and how I can fix it?
EDIT:
I have included code to stop the timer after the textblock has been updated with the hopes that solves possible multiple Tick callbacks but nothing still.
It's not that TEXT_TIMER value is reducing, but _textTimer is not stopping, so you have multiple timer ticks.
Try adding _textTimer.Stop() at the start of updateText() method.
On Dan Bryant's advice:
My program flow was registering for the Tick event multiple times beacuse I put it into the updateText method which got called multiple times during program run. All I had to do was move that line of code where the Tick event is registered, _textTimer.Tick += _textTimer_Tick; into the constructor, i.e after InitializeComponent() and problem solved!
i have a timer that changes a label's text each tick. For some reson, it stop and does not continue looping. Why?
private int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
string[] arr4 = new string[3]; // 4
arr4[0] = "one";
arr4[1] = "two";
arr4[2] = "three";
if (count == 4)
{
count = 0;
}
toolStripStatusLabel1.Text = arr4[count];
count++;
}
Also, when my form loads, the label's text is blank. Then it goes to arr4[0]. When it loops again, the text starts at arr[0]. Why is the text blank first, and how do i fix it?
Looks like your original question was answered in the comments. I'll answer your second question from the comments.
Your timer1_Tick event doesn't execute immediately when your program starts. The first time it executes is after 5000ms, in your case. So the label will show blank at first, then change to the value of arr4[0]. If you don't want that, you could:
set the value of the label in the designer at design time
set the value of the label in the constructor at run time
pull the creation of the array out of the timer tick event so you're not recreating it every 5 seconds, make it a class variable, and create it in the constructor and then set the label to arr4[0] immediately after creating it