0

如何从窗口标题中获取进程 ID?我需要从窗口标题中获取 pid,在找到它之后,我需要检查具有该 pid 的进程是否正在运行,如果它没有运行,我通过更改 _state.wait 来暂停后台工作程序。

这是我尝试过的:

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int i = 1;
            List<string> proctxt = new List<string>();

            while (true)
            {
                _state.Wait();


                if (i == 1)
                {
                    Process[] processlist = Process.GetProcesses();
                    foreach (Process Proc in processlist)
                    {
                        string text = Proc.MainWindowTitle + " = " + Proc.Id.ToString();
                        proctxt.Add(text);
                    }
                }

                if ( i == 2)
                {
                    int index = proctxt.FindIndex(a => a.Contains("Bot")) + 1;
                    string pid = proctxt[index];
                }


                if (proctxt.Contains("Bot") && i == 1)
                {
                    i++;
                }


                if (!proctxt.Contains("Bot") && i == 2)
                {
                    i--;
                    this.Invoke(new MethodInvoker(delegate { button8.Enabled = true; }));
                    this.Invoke(new MethodInvoker(delegate { button3.Enabled = false; }));
                    this.Invoke(new MethodInvoker(delegate { button4.Enabled = false; }));
                    this.Invoke(new MethodInvoker(delegate { _state.Paused = true; }));
                }
                proctxt.Clear();
                Thread.Sleep(300);
            }
        }
4

1 回答 1

0

这就是我从窗口标题获得进程 ID 的方式:

private void function1()
        {
            Process[] processlist = Process.GetProcessesByName("my process");

            string title = "title";
            string procID;
            
            foreach (Process process in processlist)
            {
                if (String.Equals(process.MainWindowTitle, title))
                {
                    procID = process.Id.ToString();
                    MessageBox.Show("This is the process ID: " + process.Id);
                    MessageBox.Show(procID);
                }
                else
                {
                    MessageBox.Show("Window not found");
                }                
            }
        }
于 2021-03-07T00:50:47.783 回答