2011-09-09 20 views
7

我開發了一個C#windows應用程序&創建了它的一個exe文件。 我想要的是,當過我嘗試運行應用程序,如果是媒體鏈接處於運行狀態比它激活該應用程序否則新的應用程序被打開如何將焦點設置爲運行狀態下的應用程序?

這意味着我不想打開同一個應用程序超過一次

+0

請檢查下面的你可能會得到你所期待的 http://stackoverflow.com/questions/2197620/how-to -set-focus-and-launch-the-already-running-application-on-button-click-event –

回答

0

將以下代碼部分用於多個實例檢查一個exe文件,以及它是否在表單加載時返回true。對於運行在您的應用程序這個功能包括using System.Diagnostics;命名空間

private bool CheckMultipleInstanceofApp() 
     { 
      bool check = false; 
      Process[] prc = null; 
      string ModName, ProcName; 
      ModName = Process.GetCurrentProcess().MainModule.ModuleName; 
      ProcName = System.IO.Path.GetFileNameWithoutExtension(ModName); 
      prc = Process.GetProcessesByName(ProcName); 
      if (prc.Length > 1) 
      { 
       MessageBox.Show("There is an Instance of this Application running"); 
       check = true; 
       System.Environment.Exit(0); 
      } 
      return check; 
     } 
3

你可以從user32.dll中調用SetForegroundWindow()和SetFocus()來做到這一點。

[DllImport("user32.dll")] 
static extern bool SetForegroundWindow(IntPtr hWnd); 

// SetFocus will just focus the keyboard on your application, but not bring your process to front. 
// You don't need it here, SetForegroundWindow does the same. 
// Just for documentation. 
[DllImport("user32.dll")] 
static extern IntPtr SetFocus(HandleRef hWnd); 

作爲參數,你傳遞你想要在前面的過程的窗口句柄和焦點。

SetForegroundWindow(myProcess.MainWindowHandle); 

SetFocus(new HandleRef(null, myProcess.Handle)); // not needed 

另請參閱the restrictions of the SetForegroundWindow Methode on msdna

+0

當我添加user32.dll時,應用程序終止 – Ayush

+0

有任何異常? –

+0

視覺工作室關閉。 – Ayush

9

使用下面的代碼將焦點設置到當前的應用程序:

 [DllImport("user32.dll")] 
     internal static extern IntPtr SetForegroundWindow(IntPtr hWnd); 

     [DllImport("user32.dll")] 
     internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); 
     ... 
     Process currentProcess = Process.GetCurrentProcess(); 
     IntPtr hWnd = currentProcess.MainWindowHandle; 
     if (hWnd != IntPtr.Zero) 
     { 
      SetForegroundWindow(hWnd); 
      ShowWindow(hWnd, User32.SW_MAXIMIZE); 
     } 
+1

對於命令或命令(第一個SetForeground ..然後ShowWindow)+1,否則它不起作用! –

+3

如果您沒有User32枚舉,可以在以下位置找到這些值:http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx – BradleyDotNET

+0

複製/粘貼的Enum可以在這裏找到:http://www.pinvoke.net/default.aspx/Enums/SHOWWINDOW_FLAGS.html。另外,ShowWindow不應該是必需的。 –

相關問題