我正在尝试使用PostMessage发送Tab键. 这是我的代码: // This class allows us to send a tab key when the the enter key// is pressed for the mooseworks mask control. public class MaskKeyControl : MaskedEdit{// [DllImport("cored
这是我的代码:
// This class allows us to send a tab key when the the enter key
// is pressed for the mooseworks mask control.
public class MaskKeyControl : MaskedEdit
{
// [DllImport("coredll.dll", SetLastError = true, CharSet = CharSet.Auto)]
// static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
[return: MarshalAs(UnmanagedType.Bool)]
// I am calling this on a Windows Mobile device so the dll is coredll.dll
[DllImport("coredll.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, uint Msg, Int32 wParam, Int32 lParam);
public const Int32 VK_TAB = 0x09;
public const Int32 WM_KEYDOWN = 0x100;
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
PostMessage(this.Handle, WM_KEYDOWN, VK_TAB, 0);
return;
}
base.OnKeyDown(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
e.Handled = true;
base.OnKeyPress(e);
}
}
当我按下输入时,代码被调用,但没有任何反应.然后我按TAB,它工作正常. (所以我发送Tab消息有问题.)
您真的不应该将与用户输入相关的Windows消息直接发布到Windows控件.相反,如果你想模拟输入,你应该依靠 SendInput API function来发送按键.此外,正如Chris Taylor在评论中提到的,如果您想使用现有的托管包装器(而不是通过P / Invoke层自己调用SendInput函数),SendKeys class可用于向应用程序发送键输入.
