我正在尝试使用 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("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 Message有问题。)
最佳答案
您真的不应该将与用户输入相关的 Windows 消息直接发布到 Windows 控件。相反,如果你想模拟输入,你应该依赖 SendInput API function而不是发送按键。
另外,正如 Chris Taylor 在他的评论中提到的,SendKeys class如果您想使用现有的托管包装器(而不是通过 P/Invoke 层自己调用 SendInput 函数),可用于将键输入发送到应用程序。
关于c# - PostMessage 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2860074/