即使最小化,也可将密钥发送到表单

时间:2017-01-15 13:21:26

标签: c# winforms key sendkeys

我有一个非常基本的C#程序,有一个简单的文本框和其他一些东西。 我有一个按钮,它触发一个计时器,我想要的是,在计时器的每个刻度我可以发送一个键到文本框(设置,以便发送一个键到表单将发送到文本框)。

我现在的代码是:

    private void timer2_Tick(object sender, EventArgs e)
    {
        SendKeys.SendWait("ciao");
    }

但这仅在表单可见并具有焦点时才有效

编辑: 由于某些原因,我不想使用" textbox.text = text"

1 个答案:

答案 0 :(得分:1)

您无法使用SendKeys,因为它会将输入发送到当前有效的窗口:

  

因为没有托管方法来激活另一个应用程序,   您可以在当前应用程序中使用此类或使用   本机Windows方法,如FindWindow和SetForegroundWindow,来   强调其他应用程序。

但是您可以使用WinAPI SendMessage函数,就像更详细地描述here一样。

考虑到您知道该文本框中包含的Form,您可以使用Control.Handle property获取其句柄,因此它将如下所示:

public static class WinApi
{
    public static class KeyBoard
    {
        public enum VirtualKey
        {
            VK_LBUTTON = 0x01,
            ...
            VK_RETURN = 0x0D
        }
    }


    public static class Message
    {
        public enum MessageType : int
        {
            WM_KEYDOWN = 0x0100
        }

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SendMessage(IntPtr hWnd, MessageType Msg, IntPtr wParam, IntPtr lParam);
    }
}

private void timer2_Tick(object sender, EventArgs e)
{
    WinApi.Message.SendMessage(
        hWnd: this.textBox.Handle, // Assuming that this handler is inside the same Form.
        Msg: WinApi.Message.MessageType.WM_KEYDOWN,
        wParam: new IntPtr((Int32)WinApi.KeyBoard.VirtualKey.VK_RETURN),
        lParam: new IntPtr(1)); // Repeat once, but be careful - actual value is a more complex struct - https://msdn.microsoft.com/en-us/library/ms646280(VS.85).aspx
}

P.S。:您可能也对PostMessage function感兴趣。

PS1:虽然此解决方案应该有效,但我想指出理想情况下您不应该使用此类机制在您自己的应用程序中执行某些操作 - 发送密钥不是总是可靠的,很难测试。通常有一种方法可以在不采用这种方法的情况下达到预期的效果。