2010-09-24 97 views
2

我有這樣的情況。 我有一個應用程序的窗口句柄。我需要激活它。我嘗試了所有這些功能,但並沒有始終工作(大多數情況下,它不是第一次工作,我必須手動點擊它才能激活它。第二次嘗試之後它可以正常工作) 原因我這樣做是因爲我的代碼寫在我需要執行的窗體的Form.Activate事件中。 應用程序是一個單一實例應用程序。當創建一個新實例時,它首先檢查是否存在任何其他進程,如果找到,則將舊進程的句柄傳遞給這些函數,以便用戶可以在舊窗體上工作。 從另一個C應用程序調用應用程序。公共靜態extern int ShowWindow(IntPtr hWnd,int nCmdShow);公共靜態extern int ShowWindow(IntPtr hWnd,int nCmdShow);需要激活一個窗口

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

    [DllImport("user32")] 
    public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); 

回答

3

SetForgroundWindow僅在其進程具有輸入焦點時纔可用。這是我使用的:

public static void forceSetForegroundWindow(IntPtr hWnd, IntPtr mainThreadId) 
{ 
    IntPtr foregroundThreadID = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero); 
    if (foregroundThreadID != mainThreadId) 
    { 
     AttachThreadInput(mainThreadId, foregroundThreadID, true); 
     SetForegroundWindow(hWnd); 
     AttachThreadInput(mainThreadId, foregroundThreadID, false); 
    } 
    else 
     SetForegroundWindow(hWnd); 
} 
+1

+1當然Windows大師雷蒙德陳[說這可能會導致您的應用程序凍結](http://stackoverflow.com/a/8081858/15639) – MarkJ 2012-09-25 12:09:24

+1

你在哪裏採取mainThreadId,這是什麼意思?謝謝! – 2014-07-14 20:55:27

0

你必須使用FromHandle得到形式:

f = Control.FromHandle(handle) 

那麼你可以可以調用激活的結果:

f.Activate() 
+1

這個問題是,它只適用於同一個應用程序中的控件。要在另一個進程中激活一個窗口,您需要使用PInvoke函數。 – TheCodeKing 2010-09-24 15:57:42

3

你需要找到使用類似窗口的窗口標題,然後激活它如下:

public class Win32 : IWin32 
{ 
    //Import the FindWindow API to find our window 
    [DllImport("User32.dll", EntryPoint = "FindWindow")] 
    private static extern IntPtr FindWindowNative(string className, string windowName); 

    //Import the SetForeground API to activate it 
    [DllImport("User32.dll", EntryPoint = "SetForegroundWindow")] 
    private static extern IntPtr SetForegroundWindowNative(IntPtr hWnd); 

    public IntPtr FindWindow(string className, string windowName) 
    { 
     return FindWindowNative(className, windowName); 
    } 

    public IntPtr SetForegroundWindow(IntPtr hWnd) 
    { 
     return SetForegroundWindowNative(hWnd); 
    } 
} 

public class SomeClass 
{ 
    public void Activate(string title) 
    { 
     //Find the window, using the Window Title 
     IntPtr hWnd = win32.FindWindow(null, title); 
     if (hWnd.ToInt32() > 0) //If found 
     { 
      win32.SetForegroundWindow(hWnd); //Activate it 
     } 
    } 
}