我有一个Windows应用程序。当我点击一个按钮时,会启动另一个进程,弹出帮助窗口。我只想打开1个窗口。因此,如果我点击按钮,我正在检查进程是否已经启动。我面临的问题是如何获得我打开的窗口的焦点。
if (processes.Length == 0)
{
Process.Start();
}
else
{
// Need to focus on the window already opened.
}
答案 0 :(得分:3)
在一篇已删除的帖子中,Vinay报告说这也对他有用:
else
{
foreach (Process process in processes)
{
if (process.Id != p.Id)
{
SwitchToThisWindow(process.MainWindowHandle, true);
return;
}
}
[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
答案 1 :(得分:1)
您可以使用last Q&A at this link描述的方法,如下所示:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ProcessWindows
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName("notepad");
if (p.Length > 0)
{
SetForegroundWindow(p[0].MainWindowHandle);
}
}
}
}