2008-05-08

Capture a key in a control or form

Last days I was in another trouble. I need to execute a function when i stroke a key (in this example Enter Key).
My primary option was asociate a button as default, then when I press Enter, i will be like I click in the button. But my form don't allow a button in this place (it doesn't look well).
But C# 2.0 has a simple solution to this case: IMessageFilter

First the controls needs implement IMessageFilter interface and overrides the PreFilterMessage method

public class MyControl: UserControl, IMessageFilter
{
...........
public bool PreFilterMessage(ref Message msg)
{
........
}
...........
}

In the PreFilterMessage method you can capture all messages and allow not enter key stroke messages pass.
const int WM_KEYDOWN = 0x100;
public bool PreFilterMessage(ref Message msg)
{
Keys keyCode = (Keys)(int)msg.WParam & Keys.KeyCode;
if (msg.Msg == WM_KEYDOWN && keyCode == Keys.Return)
{
DoSomeAction();
return true;
}
return false;
}


If you implement this code in a UserControl or in a Form, it will seem don't to work. I'ts because you need activate the filter:

Application.AddMessageFilter(MyControlInstance);

As you can imagine, using this workaround reduces your application perfomance.

No comments: