【问题标题】:PostMessage does not seem to be workingPostMessage 似乎不起作用
【发布时间】:2010-05-18 18:47:46
【问题描述】:

我正在尝试使用 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 有问题。)

【问题讨论】:

  • 我添加了 compact-framework 标签,你的一些答案不是针对 compact 框架的。
  • @Chris Taylor - 谢谢。我应该在我问的时候补充一下。

标签: c# compact-framework pinvoke sendmessage postmessage


【解决方案1】:

您确实不应该将与用户输入相关的 Windows 消息直接发布到 Windows 控件。相反,如果您想模拟输入,您应该依靠SendInput API function 来发送按键。

此外,正如 Chris Taylor 在他的评论中提到的,SendKeys class 可用于在您想要使用现有托管包装器的情况下将关键输入发送到应用程序(而不是自己通过 P/ 调用 SendInput 函数)调用层)。

【讨论】:

  • 对于托管代码,SendKeys 可能是更好的选择。 msdn.microsoft.com/en-us/library/…
  • 我最终使用了 keybd_event 函数。它位于 Windows Mobile 设备上的 coredll.dll 中。这是最接近的,所以我点头。
【解决方案2】:

关于关键事件的 PostMessage 确实很奇怪。

在这种情况下,带有 KEYDOWN、KEYPRESS、KEYUP(三个调用)的 SendMessage 可能会更好。

【讨论】:

    【解决方案3】:

    作为向控件发送输入消息的替代方法,您可以更明确地执行以下操作。

    protected override void OnKeyDown(KeyEventArgs e)
    {
      if (e.KeyCode == Keys.Enter)
      {
        if (Parent != null)
        {
          Control nextControl = Parent.GetNextControl(this, true);
          if (nextControl != null)
          {
            nextControl.Focus();
            return;
          }
        }
      }
      base.OnKeyDown(e);
    }
    

    这将在按下回车键时将焦点设置到父控件上的下一个控件。

    【讨论】:

      猜你喜欢
      • 2016-11-29
      • 2016-02-01
      • 2020-09-23
      • 2010-12-05
      • 2011-06-14
      • 2015-01-10
      • 2016-02-24
      • 2011-01-18
      • 2018-06-20
      相关资源
      最近更新 更多