【问题标题】:Send key to a form even when minimized即使最小化也将密钥发送到表单
【发布时间】:2023-03-12 08:03:01
【问题描述】:

我有一个非常基本的 C# 程序,带有一个简单的文本框和其他一些东西。 我有一个按钮,它触发一个计时器,我想要的是每次计时器的滴答声我都可以向文本框发送一个键(设置为向表单发送一个键会将其发送到文本框)。

我现在的代码是:

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

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

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

【问题讨论】:

  • 您不能使用 SendKeys() 来定位最小化的表单。 SendKeys() 仅适用于当前活动并具有焦点(在用户面前的屏幕上打开)的应用程序。对于最小化的应用程序,您必须获得目标 TextBox 的直接 句柄(可能使用 FindWindow()/EnumWindows()),然后使用 SendMessage()/PostMessage() 向其发送击键.
  • 您可以在停用之前激活窗口和发送键:stackoverflow.com/questions/41215435/…

标签: c# winforms key sendkeys


【解决方案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感兴趣。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 2020-12-31
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    相关资源
    最近更新 更多