加上设置窗口到最前的辅助方法

This commit is contained in:
lindexi 2020-08-13 22:49:32 +08:00
parent 35eb871040
commit 7151fec7b8
2 changed files with 46 additions and 0 deletions

View File

@ -152,5 +152,44 @@ namespace HandyControl.Tools
public static IntPtr GetHandle(this Window window) => new WindowInteropHelper(window).EnsureHandle();
public static HwndSource GetHwndSource(this Window window) => HwndSource.FromHwnd(window.GetHandle());
/// <summary>
/// 让窗口激活作为前台最上层窗口
/// </summary>
/// <param name="window"></param>
public static void SetWindowToForegroundWithAttachThreadInput(Window window)
{
// [WPF 让窗口激活作为前台最上层窗口的方法 - lindexi - 博客园](https://www.cnblogs.com/lindexi/p/12749671.html)
var interopHelper = new WindowInteropHelper(window);
// 以下 Win32 方法可以在 https://github.com/kkwpsv/lsjutil/tree/master/Src/Lsj.Util.Win32 找到
var thisWindowThreadId = InteropMethods.GetWindowThreadProcessId(interopHelper.Handle, out _);
var currentForegroundWindow = InteropMethods.GetForegroundWindow();
var currentForegroundWindowThreadId =
InteropMethods.GetWindowThreadProcessId(currentForegroundWindow, out _);
// [c# - Bring a window to the front in WPF - Stack Overflow](https://stackoverflow.com/questions/257587/bring-a-window-to-the-front-in-wpf )
// [SetForegroundWindow的正确用法 - 子坞 - 博客园](https://www.cnblogs.com/ziwuge/archive/2012/01/06/2315342.html )
/*
  1.FindWindow
    2.AttachThreadInput
    3.ShowWindow(/)
    4.Z OrderSetWindowPos使之最上Z Order,
    5.SetForegroundWindow
*/
InteropMethods.AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, true);
window.Show();
window.Activate();
// 去掉和其他线程的输入链接
InteropMethods.AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, false);
// 用于踢掉其他的在上层的窗口
if (window.Topmost != true)
{
window.Topmost = true;
window.Topmost = false;
}
}
}
}

View File

@ -43,6 +43,13 @@ namespace HandyControl.Tools.Interop
[DllImport(InteropValues.ExternDll.User32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport(InteropValues.ExternDll.User32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool AttachThreadInput(in uint currentForegroundWindowThreadId,
in uint thisWindowThreadId, bool isAttach);
[DllImport(InteropValues.ExternDll.User32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern IntPtr GetForegroundWindow();
[DllImport(InteropValues.ExternDll.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern IntPtr OpenProcess(InteropValues.ProcessAccess dwDesiredAccess,
[MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwProcessId);