C# WinForm 获取句柄与置顶窗体
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow(); //获得本窗体的句柄
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
public static extern bool SetForegroundWindow(IntPtr hWnd);//设置此窗体为活动窗体
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode)]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
//定义变量,句柄类型
public IntPtr Handle1;
Handle1 = new IntPtr(0);
Handle1 = FindWindow(null, Name);
if (Handle1 != IntPtr.Zero){
SetForegroundWindow(Handle1);//置顶
}
SetForegroundWindow失效的问题
试验出来的SetForegroundWindow失效的情况之一,是窗口被最小化了。解决的方法是
::ShowWindow(wnd_, SW_SHOWNORMAL);
::SetForegroundWindow(wnd_);
网上的万金油做法是
HWND hForeWnd = ::GetForegroundWindow();
DWORD dwForeID = ::GetWindowThreadProcessId(hForeWnd, NULL);
DWORD dwCurID = ::GetCurrentThreadId();
::AttachThreadInput(dwCurID, dwForeID, TRUE);
::ShowWindow(wnd_, SW_SHOWNORMAL);
::SetWindowPos(wnd_, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
::SetWindowPos(wnd_, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
::SetForegroundWindow(wnd_);
::AttachThreadInput(dwCurID, dwForeID, FALSE);
感觉SetWindowPos也不是必须的
本文详细介绍了在C#WinForm中如何通过获取窗体句柄并使用SetForegroundWindow函数实现窗体置顶功能,同时针对SetForegroundWindow失效情况提供了多种解决方案,包括显示窗口、调整窗口位置及线程输入附着等方法。

2万+

被折叠的 条评论
为什么被折叠?



