gpt4 book ai didi

c# - Sendkey 到后台程序

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:40 25 4
gpt4 key购买 nike

我正在尝试创建一个应用程序,它将以设定的时间间隔(毫秒)在后台向应用程序(通过进程或窗口)发送击键。我在这个主题上找到了几个不同的答案,但我需要一个 ELI5(像我 5 岁一样解释)答案。作为测试,我使用我发现的以下代码将 key 发送到记事本。

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

}
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com