Skip to content

C# Form Control Selection without Focus()

September 3, 2012

I recently came across a problem with some code on a handheld device. The code in question was using reflection to override the normal interface for the app, it looked and worked good except one large problem.

The code was being used on a device that had a barcode reader but the cursor needs to be in the textbox for the program to register new barcodes that are read. This normally wouldn’t be a problem because you can use This.Focus() in your form to give the textbox control focus. In my case because we are using reflection to override the natural form it was a problem.

The solution I came up with is a Hack but it works!

First I init this code at the top of my class.

static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);

private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;

Then just before my code looses focus I init my timer.

myTimer.Interval = 100;
myTimer.Tick += new EventHandler(myTimer_Tick);

Then I make the mouse click!

void myTimer_Tick(object sender, EventArgs e)
int X = 886;
int Y = 554;
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(X, Y);



From → .NET

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: