public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
Process process;
public Form1()
{
process = Process.GetProcesses()
.Where(x => x.ProcessName == "MyProcessName")
.FirstOrDefault();
//init global keypress as needed
}
void gkh_KeyUp(object sender, KeyEventArgs e)
{
IntPtr handle = GetForegroundWindow();
uint processID = GetWindowThreadProcessId(handle, IntPtr.Zero);
if (p2.Threads.OfType<ProcessThread>().Any(x => x.Id == Convert.ToInt32(processID)))
{
//keypress in MyProcessName
}
e.Handled = true;
}
擊鍵進入在前景中的窗口。所以你需要GetForegroundWindow()和GetWindowThreadProcessId()。 –
@Hans Passant:這很有幫助。請發佈答案,以便我可以將此標記爲已解決。 'Process process = Process.GetProcesses() .Where(x => x.ProcessName ==「MyProcessName」) .FirstOrDefault(); // ... IntPtr handle = GetForegroundWindow(); uint processID = GetWindowThreadProcessId(handle,IntPtr.Zero); if(p2.Threads.OfType()。Any(x => x.Id == Convert.ToInt32(processID))) // success' –
isHuman
只需自行發佈解決方案並將其標記爲答案。 –