C# WinForm 获取句柄与置顶窗体

本文详细介绍了在C#WinForm中如何通过获取窗体句柄并使用SetForegroundWindow函数实现窗体置顶功能,同时针对SetForegroundWindow失效情况提供了多种解决方案,包括显示窗口、调整窗口位置及线程输入附着等方法。

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也不是必须的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值