用keybd_event产生一个键盘事件, 示例代码如下
void SetNumLock( BOOL bState )
{
BYTE keyState[256];
GetKeyboardState((LPBYTE)&keyState);
if( (bState && !(keyState[VK_NUMLOCK] & 1)) ||
(!bState && (keyState[VK_NUMLOCK] & 1)) )
{
// Simulate a key press
keybd_event( VK_NUMLOCK,
0x45,
KEYEVENTF_EXTENDEDKEY | 0,
0 );
// Simulate a key release
keybd_event( VK_NUMLOCK,
0x45,
KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
0);
}
}
void main()
{
SetNumLock( TRUE );
}
写了一个函数和上面的例子差不多,也是调用keybd_event,发送keyUp和keyDown消息,现在我想做一个单元测试,当我按下一个键,怎么获取这个键消息,验证程序有正确执行?程序不是在Form下写的,和示例的程序差不多。还请高手解答
你想捕获全局的吗,那可以用过滤器
C# code
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public class TestMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
// Blocks all the messages relating to the left mouse button.
if (m.Msg >= 513 && m.Msg <= 515)
{
Console.WriteLine("Processing the messages : " + m.Msg);
return true;
}
return false;
}
}
窗体初始化时加上
TestMessageFilter filter = new TestMessageFilter();
Application.AddMessageFilter(filter);
WinForm可以这样实现
# code
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Up)
{
//do something
}
……