发送key到后台程序
本文关键字:程序 后台 key 发送 | 更新日期: 2023-09-27 17:50:04
我试图创建一个应用程序,将发送一个击键到应用程序(通过进程或窗口)在后台以设定的间隔(毫秒)。关于这个话题,我找到了几个不同的答案,但我需要一个像我一样解释的答案。作为测试,我使用了我找到的以下代码来发送键到记事本。
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}");
}
}
}
在c#//SendKeys中找到答案。SendWait仅在最小化进程'es窗口时起作用
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}");
}
}
}