C#激活并前置窗口(不在任务栏闪动)

微软的文档中说:

An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user.

 

只有是同一线程时才不会在任务栏闪烁而直接前置。

 1 void BringWindowToFront()
 2 { 
 3      [DllImport("user32")]
 4         static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
 5 
 6         [DllImport("user32")]
 7         static extern bool AttachThreadInput(IntPtr idAttach, IntPtr idAttachTo, bool fAttach);
 8         [DllImport("user32")]
 9         static extern IntPtr GetForegroundWindow();
10         [DllImport("user32")]
11         static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
12         [DllImport("kernel32")]
13         static extern IntPtr GetCurrentThreadId();
14      IntPtr currentHwnd = GetForegroundWindow();
15         IntPtr intPtr = this.Handle;
16         if (currentHwnd!=intPtr)
17         {
18            IntPtr currentActiveThreadId = GetWindowThreadProcessId(currentHwnd, IntPtr.Zero);
19            IntPtr thisThreadId = GetCurrentThreadId();
20 
21        AttachThreadInput(thisThreadId, currentActiveThreadId, true);  //将线程的输入处理机制绑定在当前激活的窗口上
26             SwitchToThisWindow(intPtr, true);
27             AttachThreadInput(thisThreadId, currentActiveThreadId, false);  //解除绑定
28          }
29 }

 

posted @ 2020-08-29 01:56  ppaw  阅读(811)  评论(0)    收藏  举报