Я хочу отправить ключи в другое приложение. В текущей версии моего кода приложение пытается вывести приложение на передний план, но у него этого не получается. Фактически, оно не должно выводить его на передний план, оно должно работать автоматически, когда приложение находится в фоновом режиме.
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace macro
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
const int VK_SPACE = 0x20;
private Thread autoPressThread;
private bool isPressing = false;
public Form1()
{
this.MaximumSize = new Size(320, 240);
this.MinimumSize = new Size(320, 240);
InitializeComponent();
}
private void StartKeyPressing(string windowName)
{
IntPtr hWnd = FindWindow(null, windowName);
if (hWnd == IntPtr.Zero)
{
MessageBox.Show("Application not found!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
while (isPressing)
{
SetForegroundWindow(hWnd);
if (GetForegroundWindow() == hWnd)
{
keybd_event(VK_SPACE, 0, 0, UIntPtr.Zero);
}
else
{
keybd_event(VK_SPACE, 0, 2, UIntPtr.Zero);
}
Thread.Sleep(100);
}
keybd_event(VK_SPACE, 0, 2, UIntPtr.Zero);
}
private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
string windowName = "Sezar2 - " + name;
isPressing = true;
autoPressThread = new Thread(() => StartKeyPressing(windowName));
autoPressThread.IsBackground = true;
autoPressThread.Start();
}
private void button2_Click(object sender, EventArgs e)
{
isPressing = false;
if (autoPressThread != null && autoPressThread.IsAlive)
{
autoPressThread.Join();
}
MessageBox.Show("Space tuşu bırakıldı.", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... pplication