Fastest way to get focused control in WinForms c#?
I'm using ProcessCmdKey in my main form window for the application to test for certain keys and give Space, Right, Left, and a few others special processing. ProcessCmdKey in the main form is called even if the user is typing in a TextBox inside a nested set of user controls. I do开发者_开发问答n't want to process the Space key when they are focused on a TextBox control, since they'd never be able to type a space. How can I test for the type of the currently focused window on an application wide basis?
You can get the window handle with this:
[DllImport("user32.dll")]
private static extern IntPtr GetFocus();
Then you can get the .NET control associated with that handle (if there is one) with Control.FromHandle.
Found something that appears to work:
[DllImport("user32.dll")]
static extern IntPtr GetFocus();
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
IntPtr wndHandle = GetFocus();
Control focusedControl = FromChildHandle(wndHandle);
if(focusedControl is DevExpress.XtraEditors.TextBoxMaskBox)
{
return base.ProcessCmdKey(ref msg, keyData);
}
...
}
精彩评论