I'm currently converting a winforms app into a WPF app and discovered the key events are significantly different in WPF. Here's a few tips and things to look out for:
I needed a way to force an application to stay on top. I thought it would be as simple as "this.Activate" in the form's deactivate event. It looked like it was trying to work - when clicking out of the app, it's start bar button would blink, but it wouldn't bring the app back on top. I then proceeded to try just about everything under the sun:
public static extern Int32 SetForegroundWindow(int hWnd);
Everything seemed to do the same thing. Finally I thought that maybe I was trying to refocus the form too soon. I decided to create a timer and delay the Activate call:
//declare the timer
private System.Timers.Timer restoreFocusTimer = new System.Timers.Timer();
//setup the timer in the constructor
restoreFocusTimer.AutoReset = false;
restoreFocusTimer.SynchronizingObject = this;
restoreFocusTimer.Interval = 1000;
restoreFocusTimer.Elapsed += new System.Timers.ElapsedEventHandler(restoreFocusTimer_Elapsed);
//define the handler
void restoreFocusTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
//enable the timer in the deactivate event (I also added a preprocessor directive so i could disable it when debugging.
private void MainForm_Deactivate(object sender, EventArgs e)
restoreFocusTimer.Enabled = true;
I had a form that didn't seem to want to follow the TabIndex that I had set on a number of controls. The cursor jumped around passed controls with a lower index and then would come back to them later. The difference between this form and others was that this form had a panel on it that hid a couple of controls until they were displayed upon the click of a radio button. I did notice that if I deleted the controls and recreated them in the order I wanted them to tab, they would tab correctly. However, starting over is a lousy fix so I dug into it a bit deeper. After debugging I found that the TabIndex on the controls within the panel were being reset. It also turns out that even though a Panel control has no mention of a TabIndex property in the Properties pane or with intellisense, it does in fact have that property. Setting the Panel's TabIndex in the form load event fixed the issue for me. To make it so I wouldn't get bit by this again, I set the panel's TabIndex to the index of the first control in the panel.
I just came off a project programming Motorola barcode canners based on Windows Mobile. The Motorola/Symbol API was top notch and provided access to everything I needed. This included an event driven API for the scanner. This meant I had a nice "Scan" event to use from within my code rather than rely on simple keyboard emulation. This great when a single barcode had multiple fields of data. I could parse everything behind the scenes without using a "capture" field on my forms.
The next project also needed a barcode scanner but would be a Winforms app rather than a mobile app. To my surprise the APIs for these usb and serial scanners were not nearly as good. Only a select few scanners supported Motorola's usb SNAPI interface, and there was no native .net support there (just a bunch of DllImports). Others had an RS232 based interface but it wasn't much better than reading raw data from the serial port. A few of the scanners supported the OPOS standard which means I could have used POS for .net but that seemed overkill for my needs.
Finally I realized there was a much simpler solution. Most of these scanners supported a keyboard emulation mode. More importantly they supported the ability to be programmed to include prefixes and suffixes in the scan. While most would use this feature to send an 'Enter' after a successful scan, I realized I could use this to send special characters to indicate the start and end of a scan and separate it from normal keyboard input. From there making my own API was simple.
There were two main points to this. The first was to monitor keypresses:
HostForm.KeyPreview = true;
this.enabled = true;
HostForm.KeyPress += new KeyPressEventHandler(KeyPressHandler);
HostForm.KeyPress -= KeyPressHandler;
The line of interest here should be the Form.KeyPreview=true. This allows you to pickup keyboard strokes at the form level rather than from the control with focus.
From there it's just a matter of looking for the started and ending characters (i chose ctrl-s and ctrl-t, ascii char 19 and 20 resp):
public void KeyPressHandler(object sender, KeyPressEventArgs e)
//if a scan has started...
if (!IsScanning && e.KeyChar == ScanStartCharacter)
IsScanning = true;
e.Handled = true;
//if a scan is in progress and is not being terminated...
else if (IsScanning && e.KeyChar != ScanEndCharacter)
//...then add the char to the buffer
e.Handled = true;
//if a scan has ended
else if (e.KeyChar == ScanEndCharacter)
e.Handled = true;
else //not scanning, pass the character on as keyboard input.
e.Handled = false;
I threw a timer in there just to make sure the scan eventually completes, even if the user forgets to program the suffix into the scanner.
That's pretty much it. The full code is attached.
There's a great article on msdn that covers the 3 different types of timers. I've basically boiled it down to this:
- Use the Forms.Timer for simple updates to the UI. For example i like to bold certain errors when they happen and then return them to a normal font. This helps the user identify when they caused the same error twice.
- Use the Threading.Timer to execute one-off processes off of the UI thread
- Use the Timers.Timer to execute recurring processes. This timer's AutoReset and Enabled properties make it much cleaner to use than Threading.Timer's Change method.
I tended to lean to Threading.Timer in most cases. When I needed to do something on the UI thread i just used Invoke. What I missed from the article is Timers.Timer's SynchronizingObject property. Simply set this to your form or something else on your UI thread, and no "InvokeRequired" code is needed to access the UI. Because of this, this timer has no become my timer of choice. The only drawback to it compared to the Threading version, is that the Threading version's callback takes an object parameter allowing you to pass some state into the callback. That's only a minor issue considering you can either create a field to temporarily store this additional data or you can create different "Elapsed" events.
Some other basic threading tips:
- Don't forget to hold a reference somewhere to your timer. If there are no references, the timer might be garbage collected before it gets a chance to fire
- Timers.Timer AutoReset is true by default. I almost always set this to false and then reset Enabled=true in the Elapsed event. This avoids any reenterance issues.
I had a TextBox that I had bound to a property on a class that implements INotifyProperyChanged. No matter what I did, I just couldn't get the TextBox to update the bound property. Each time the text box just reverted back to it's original value. A simplified version of my class looked like this:
public class KeyboardWedgeScanner : INotifyPropertyChanged
public TimeSpan ScanTimeout
timeoutTimer.Interval = value.TotalMilliseconds;
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(String propertyName)
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
In my form I bound the textbox with this in my constructor:
InScannerTimeout.DataBindings.Add("Text", scanner, "ScanTimeout");
This is exactly how a bound TextBoxes in another project and it worked fine there. I messed around with the DataSourceUpdateMode parameter on an overload of Add but that didn't help either. It wasn't until I set the formattingEnabled property to true did it start working:
InScannerTimeout.DataBindings.Add("Text", scanner, "ScanTimeout", true);
The only thing I can think of is that something about the TimeSpan class requires this to return the TextBox.Text's string value back into an instance of TimeSpan.