2011-06-03 59 views

回答

11

如果你没有的窗口句柄,使用此之前:

[DllImport("user32.dll", SetLastError = true)] 
static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 

现在,假设你有一个句柄应用程序窗口:

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

这将使任务栏如果另一个窗口有键盘焦点,则闪烁

如果您想强制窗口来到前面,请使用ForceForegroundWindow(样本实施)。

+0

SetForegroundWindow似乎做什么,我需要到目前为止,但是我在尝试调用ForceForegroundWindow(“无法找到DLL‘user32.dll中’名为‘ForceForegroundWindow’的切入点。”) – 2011-06-03 15:07:17

+0

时错误我的错误是用户自制的功能。编辑后。 – 2011-06-03 15:49:53

+0

就我而言,除了这个之外,我还必须使用'BringWindowToTop'。 ForceForegroundWindow精美地解决了我的问题。谢谢! – 2012-06-05 20:10:32

7

这已证明是非常可靠的。 ShowWindowAsync函数专门为由不同线程创建的窗口而设计。 SW_SHOWDEFAULT确保窗口在显示前恢复为,然后激活。

[DllImport("user32.dll", SetLastError = true)] 
    internal static extern bool ShowWindowAsync(IntPtr windowHandle, int nCmdShow); 

    [DllImport("user32.dll", SetLastError = true)] 
    internal static extern bool SetForegroundWindow(IntPtr windowHandle); 

然后使呼叫:

ShowWindowAsync(windowHandle, SW_SHOWDEFAULT); 
ShowWindowAsync(windowHandle, SW_SHOW); 
SetForegroundWindow(windowHandle); 
+0

工程就像一个魅力,而我尝试过的其他代码都失败了。 – 2015-09-04 10:30:24

9
[DllImport("user32.dll")] 
    public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow); 
    [DllImport("user32.dll")] 
    public static extern bool SetForegroundWindow(IntPtr WindowHandle); 
    public const int SW_RESTORE = 9; 

ShowWindowAsync方法用于显示的最小化的应用程序和SetForegroundWindow方法用于带来正面背面应用。

您可以使用这些方法,因为我在我的应用程序中使用了我的应用程序的Skype软件。按钮点击

private void FocusSkype() 
    { 
     Process[] objProcesses = System.Diagnostics.Process.GetProcessesByName("skype"); 
     if (objProcesses.Length > 0) 
     { 
      IntPtr hWnd = IntPtr.Zero; 
      hWnd = objProcesses[0].MainWindowHandle; 
      ShowWindowAsync(new HandleRef(null,hWnd), SW_RESTORE); 
      SetForegroundWindow(objProcesses[0].MainWindowHandle); 
     } 
    } 
+0

谢谢。节省了我的时间。 :) – 2014-09-30 10:11:15