【问题标题】:C# / Send keys combination (CTRL+S) to another windowC# / 将组合键 (CTRL+S) 发送到另一个窗口
【发布时间】:2020-09-14 19:01:40
【问题描述】:

我正在尝试将组合键发送到另一个类似的程序:

// keydown ctrl
SendMessage(windowBracketsKeyListener, 0x100, (IntPtr)VK_CONTROL, (IntPtr)0x001D0001); 
// keydown S
SendMessage(windowBracketsKeyListener, 0x100, (IntPtr)VK_S, (IntPtr)0x001F0001); 
SendMessage(windowBracketsKeyListener, 0x102, (IntPtr)115, (IntPtr)0); 
// keyup ctrl 
SendMessage(windowBracketsKeyListener, 0x101, (IntPtr)VK_CONTROL, (IntPtr)0xC01D0001); 

到最后一行我有一个错误(看下图)。

我发送与 Spy++ 相同的命令。所以首先我自动尝试在窗口上单击 CTRL+S 然后检查我在 Spy++ 中得到的内容并编写了相同的命令。

错误:

System.OverflowException: 'Arithmetic operation resulted in an overflow.'
  • 好吧,老实说,我使用的不是 Spy++,而是 Window Detective。

【问题讨论】:

  • C# 十六进制文字是有符号的,这可能会导致符号位问题。您可能需要在十六进制值上添加 u 后缀,或者使用 (IntPtr)unchecked { (uint) 0xhexvalue } 来确保不会启动符号扩展。
  • 第三行看起来很可疑。您是否要为 S 发送密钥?您在图像中的 cmets 与您所调用的不匹配。难道你不想做:keydown ctrl、keydown s、keyup s、keyup ctrl?完整的异常和堆栈跟踪会很有用。
  • @BenVoigt ,我不确定你的理解是否正确。当我不转换为 IntPtr 时出现错误:“无法从 'uint' 转换为 'System.IntPtr'”
  • @shox ,图像上的代码很脏。第二和第三行有发送“s”键。并且“s”键发送没有问题。正如您在 Window Detective 上看到的一样,但我在第 4 行出现错误。

标签: c# winapi window sendkeys sendmessage


【解决方案1】:

伪造WM_KEYDOWN/WM_KEYUP 消息没有多大意义,只发送它们生成的消息。只有两条WM_CHAR 消息。

请改为use SendKeys.Send(String) Method

指定应按住 SHIFT、CTRL 和 ALT 的任意组合 在按下其他几个键的同时向下,附上这些键的代码 括号中的键。例如,指定在按住 SHIFT 的同时 按下 E 和 C,使用“+(EC)”。指定在按住 SHIFT 的同时 按下 E 后按 C 不加 SHIFT,使用“+EC”。

以下示例适用于我:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Test
{
    static class Program
    {
        [DllImport("user32.dll")]
        public static extern int SetForegroundWindow(IntPtr hWnd);
        static void Main()
        {

            Process[] processes = Process.GetProcessesByName("notepad"); //notepad used be test

            foreach (Process proc in processes)
            {
                SetForegroundWindow(proc.MainWindowHandle);
                SendKeys.SendWait("^(s)");
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多