2010-09-24 96 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 
     } 
    } 
}