I am working on a C# WinForms app, and I want it to be able to pop open a non-modal dialog which will get redrawn and be interactive at the same time as the main window/form.
The main window is using a SerialPort and displaying data transfer counts, which are continually increasing via a SerialDataReceivedEventHandler.
I can use ShowDialog() which seems to work in a modal fashion, but the main window data counters freeze while the dialog is in use, and I think eventually the serial buffers are overrun.
I think I want to use Show(), but if I do this the dialog appears on screen half-drawn, then is not drawn or interactive any more (gets trashed if I drag another window across it). It stays onscreen until I close the main app window.
Perhaps I should be starting another thread or, likely, am just doing something wrong. I don't usually do C# or Windows programming (maybe you can tell.)
Edit after comments (thanks, commenters):
I think maybe most things are getting run under whatever thread the serial receive event handler gets called under. When starting up my app I create a class to handle the serial, which includes:
com.DataReceived += new SerialDataReceivedEventHandler(SerialRxHandler);
The only code that I have written to care about threads is some functions to update the counters and log listbox, which I found had to be wrapped with some InvokeRequired to stop me getting complaints about thread switching:
delegate void SetCountDelegate(TextBox tb, int count);
internal void SetCount(TextBox tb, int count) {
// thread switch magic
if (InvokeRequired) {
BeginInvoke(new SetCountDelegate(SetCount), new object[] { tb, count });
} else {
tb.Text = String.Format("{0}", count);
}
}
So maybe I shouldn't be trying to Show() a form on this 开发者_如何转开发thread. Another InvokeRequired block, or should I be doing things completely differently?
Suppose I'll answer myself..
Prompted by commenters and a bit of thinking, I did an Invoke() to switch to the UI thread before trying to create and Show() my child dialog. That worked.
精彩评论