C#将控制台应用程序挂钩到记事本

7 c# hook process

我想要做的是创建一个简单的Windows应用程序,它将自己挂钩到NotePad,然后模拟击键.我有打开NotePad的过程,将它带到前台然后模拟被按下的数字1.但是,如果我点击记事本,那么任何活动状态都会变成输入内容.

如何将此应用程序绑定到记事本,以便我可以单击并键入任何内容,此应用程序仍将命令推入记事本?

这是我用来模拟按键的DLL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using WindowsInput;

namespace NotePadTesting
{
    class Program
    {
        [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);


        static void Main(string[] args)
        {

            Process[] processes = Process.GetProcessesByName("notepad");

            if (processes.Length == 0)
            {

                Process.Start("notepad.exe");
                processes = Process.GetProcessesByName("notepad");

            }
            if (processes.Length == 0)
            {
                throw new Exception("Could not find notepad huh....");
            }

            IntPtr WindowHandle = processes[0].MainWindowHandle;
            SetForegroundWindow(WindowHandle);

            for (int i = 0; i < 500; i++)
            {
                System.Threading.Thread.Sleep(100);
                InputSimulator.SimulateKeyPress(VirtualKeyCode.VK_1);

            }


        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 2

如果您已经拥有要输入的窗口句柄,则可以使用PostMessage函数。你只需要谷歌搜索虚拟键码即可。