2

I'm trying to create an application that will send a keystroke to an application (by process or window) in the background at a set interval(ms). I've found a few different answers on this topic but I need an ELI5 (explain like I'm 5) answer. As a test I used the following code I found to send keys to notepad.

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace TextSendKeys
{
    class Program
    {
        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        static void Main(string[] args)
        {
            Process notepad = new Process();
            notepad.StartInfo.FileName = @"C:\Windows\Notepad.exe";
            notepad.Start();

            // Need to wait for notepad to start
            notepad.WaitForInputIdle();

            IntPtr p = notepad.MainWindowHandle;
            ShowWindow(p, 1);
            SendKeys.SendWait("ABC");
        }
    }
}

This code allows me to send the keystrokes to notepad. It opens notepad, but can't do it in the background.

Answer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Threading;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;


namespace TextSendKeys
{
    class Program
    {

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);

    static void Main(string[] args)
    {
        Process[] processes = Process.GetProcessesByName("process name here");
        Process game1 = processes[0];

        IntPtr p = game1.MainWindowHandle;

        SetForegroundWindow(p);
        SendKeys.SendWait("{1}");
        Thread.Sleep(1000);
        SendKeys.SendWait("{1}");

        }
    }
}
Advancin
  • 171
  • 1
  • 2
  • 12

1 Answers1

2

Found the answer at C# // SendKeys.SendWait works only when process'es window is minimzed

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Threading;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;


namespace TextSendKeys
{
    class Program
    {

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);

    static void Main(string[] args)
    {
        Process[] processes = Process.GetProcessesByName("process name here");
        Process game1 = processes[0];

        IntPtr p = game1.MainWindowHandle;

        SetForegroundWindow(p);
        SendKeys.SendWait("{1}");
        Thread.Sleep(1000);
        SendKeys.SendWait("{1}");

        }
    }
}
Community
  • 1
  • 1
Advancin
  • 171
  • 1
  • 2
  • 12