需要激活一个窗口

我有这种情况。 我有一个应用程序的窗口句柄。 我需要激活它。 我尝试了所有这些function,但总是没有工作。(大多数时候,它不能在第一次工作,我将不得不手动点击它来激活它。第二次尝试以后它工作正常)我之所以如此我这样做是因为我有代码写在Form.Activate事件的forms,我需要执行。 应用程序是单实例应用程序。 创建新实例时,它首先检查是否存在任何其他进程,如果找到,则将旧进程的句柄传递给这些函数,以便用户可以处理旧表单。 从不同的C应用程序调用应用程序。 [DllImport(“user32.dll”)] public static 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); 

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 ); } 

您需要使用Window title之类的东西找到窗口,然后按如下方式激活它:

 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 } } } 

您必须使用FromHandle获取表单:

 f = Control.FromHandle(handle) 

那么你可以在结果上调用Activate:

  f.Activate()