首页 > C#如何模拟系统按键

C#如何模拟系统按键

准备写一个需要模拟按键的小程序,想尝试通过模拟按键的方式来触发特定软件的功能,尝试了SendMessage函数,但是没有成功。请问应该如何做呢?


好吧,我又自己找到答案了。虽然这个答案有点纠结。
首先,使用DllImport引入两个函数:

// Get a handle to an application window.
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName,
    string lpWindowName);

// Activate an application window.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

然后首先使用FindWindow函数获取到需要按键的窗口句柄,以计算器为例。这里体现了这个方法的局限性,就是似乎不能触发全局快捷键。

// Get a handle to the Calculator application. The window class
// and window name were obtained using the Spy++ tool.
IntPtr calculatorHandle = FindWindow("CalcFrame","Calculator");

然后使用SetForegroundWindow函数将这个窗口调到最前。

SetForegroundWindow(calculatorHandle);

接下来就可以直接使用SendKeys.SendWait之类的发送按键了。

SendKeys.SendWait("111");
SendKeys.SendWait("*");
SendKeys.SendWait("11");
SendKeys.SendWait("=");

完整代码如下:

using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Windows.Forms;
// Get a handle to an application window.
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName,
    string lpWindowName);

// Activate an application window.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

// Send a series of key presses to the Calculator application.
private void button1_Click(object sender, EventArgs e)
{
    // Get a handle to the Calculator application. The window class
    // and window name were obtained using the Spy++ tool.
    IntPtr calculatorHandle = FindWindow("CalcFrame","Calculator");

    // Verify that Calculator is a running process.
    if (calculatorHandle == IntPtr.Zero)
    {
        MessageBox.Show("Calculator is not running.");
        return;
    }

    // Make Calculator the foreground application and send it 
    // a set of calculations.
    SetForegroundWindow(calculatorHandle);
    SendKeys.SendWait("111");
    SendKeys.SendWait("*");
    SendKeys.SendWait("11");
    SendKeys.SendWait("=");
}

注意如果是命令行程序的话需要手动添加System.Windows.Forms引用,否则找不到SendKeys类。

【热门文章】
【热门文章】