Focus() not working?

Posted by Jeffrey Vanneste at 03:33 PM on November 01, 2004

Category: Development

We had this strange problem at work today where we would give focus to a TextBox by calling the Focus() method and for some reason the TextBox got focus but yet the cursor was still not on the TextBox. How do we know it had focus? Well, we would press tab and the next button in the tab order got focus. Pressing shift+tab hid the focus again but pressing shift+tab one more time and we would end up on the control before the TextBox.
If we switched to any other window and came back to the form or minimized and restored the form the focus would all work fine. Our solution, instead of calling the Focus() method on the TextBox we simulated a mouse click on the TextBox:

SendMessage(this.textBox.Handle, Win32.WM_LBUTTONDOWN, 0, 0);
SendMessage(this.textBox.Handle, Win32.WM_LBUTTONUP, 0, 0);

My other discovery today was that I don't need to use Win32 imports to send Shift+Tab keyboard strokes like this:

byte[] pbKeyState = new byte[256];
Win32.GetKeyboardState(pbKeyState);
pbKeyState[(int)Win32.VK.SHIFT] |= 0x80;
Win32.SetKeyboardState(pbKeyState);
Win32.PostMessage( this.Handle, Win32.WM_KEYDOWN, (System.UInt32)Win32.VK.TAB, 0); 
Win32.PostMessage( this.Handle, Win32.WM_KEYUP, (System.UInt32)Win32.VK.TAB, 0); 
System.Windows.Forms.Application.DoEvents();
Win32.GetKeyboardState(pbKeyState);
pbKeyState[(int)Win32.VK.SHIFT] ^= 0x80;
Win32.SetKeyboardState(pbKeyState);

It's so much easier to just do it like this:

System.Windows.Forms.SendKeys.Send("+{TAB}");

Silly me :) And one final note, pinvoke.net is an absolutely fabulous site for finding different Win32 structures and imports for use with .NET.