我正在尝试创建一个应用程序,该应用程序将以设定的间隔(ms)在后台向应用程序(通过进程或窗口)发送按键。我在这个主题上找到了一些不同的答案,但我需要一个ELI5(像我这样解释)答案。作为测试,我使用以下代码将密钥发送到记事本。
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");
}
}
}
此代码允许我将击键发送到记事本。它打开记事本,但不能在后台执行。
答案
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}");
}
}
}
答案 0 :(得分:2)
在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}");
}
}
}