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

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#)