2011-06-29 33 views
2

我有一个Windows应用程序。当我点击一个按钮时,另一个进程开始弹出帮助窗口。我只想打开1个窗口。所以如果我点击按钮,我正在检查过程是否已经开始。我面临的问题是如何获得我打开的窗口的焦点。如何找回C#Windows窗体中已打开窗口的焦点

if (processes.Length == 0) 
{ 
     Process.Start(); 
} 
else 
{ 
    // Need to focus on the window already opened. 
} 

回答

3

在删除后,维奈报道,这也为他工作:

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

您可以使用由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); 
      } 
     } 
    } 
}