将字符串与进程名称进行比较

本文关键字:比较 进程名 字符串 | 更新日期: 2023-09-27 17:55:26

我想这样做...如果记事本在前台,它会打开计算器...如果另一个程序处于打开状态,则不执行任何操作...记事本是OEPN手动的..."开始,记事本"...我有这个代码来"查看"记事本是否打开......不知道如何继续 D:我知道我必须使用

if (switch == 0)
{
if (SOMETHING == "Notepad")
{
   var switch = 1 //so it doesnt enters in a loop
   OPEN CALCULATOR //irrelevant, i may use another part of otrher code that is already working
   }
}

"switch"变量从代码开头开始就是0,所以这将起作用(希望)

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
Process GetActiveProcess()
{
    IntPtr hwnd = GetForegroundWindow();
    uint pid;
    GetWindowThreadProcessId(hwnd, out pid);
    Process p = Process.GetProcessById((int)pid);
    return p;
}

问题是我不知道在"SOMETHING"上放什么来使用其余的代码,以及在哪里或如何使用 If...

将字符串与进程名称进行比较

你可以做:

Process[] notePadProcesses  = Process.GetProcessesByName("notepad.exe");
IntPtr activeWindowHandle = GetForegroundWindow();
if (notePadProcesses != null && notePadProcesses.Length > 0
    && notePadProcesses.Any(p=>p.MainWindowHandle == activeWindowHandle))
{
 // notepad is open in the foreground.
 switch = 1;
 // OPEN Calculator or whatever you need to.
}
else
{
 // notepad is either not open, or not open in the foreground.
}

基本上,我们使用 C# 友好的 Process 类来查找所有打开的记事本进程。然后找出它是否是一个活动进程并从那里开始。

请小心使用 ActiveWindow 逻辑,因为很多时候,它们会导致争用条件,当您确定某个进程处于活动状态并尝试执行某些操作时,它可能不再是活动进程。 小心行事。