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可用于向应用程序发送键输入.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...