微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – PostMessage似乎不起作用

我正在尝试使用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 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可用于向应用程序发送键输入.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐