C# Hooking a Console Application to Notepad

Viewed 2048

What i want to do is create a simple windows application that will hook itself onto NotePad and then simulate a keystroke. I have the process of opening up NotePad, bringing it to the foreground and then simulate the number 1 being pressed. However, if I click off of notepad, whatever is active becomes what is being typed in.

How do I bind this application to notepad, so that I can click and type in whatever, and this application will still push commands into notepad?

This is the DLL i'm using to simulate keypressing:

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);

            }


        }
    }
}
2 Answers
Related