WPF 让窗口激活作为前台最上层窗口的方法

Posted lonelyxmas

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF 让窗口激活作为前台最上层窗口的方法相关的知识,希望对你有一定的参考价值。

原文:WPF 让窗口激活作为前台最上层窗口的方法

原文参照林大佬的博客WPF 让窗口激活作为前台最上层窗口的方法

我只提供下,我使用的代码

技术图片
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

[DllImport("user32.dll")]
private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

public static void SetWindowToForegroundWithAttachThreadInput(Window window)
{
    var interopHelper = new WindowInteropHelper(window);
    var thisWindowThreadId = GetWindowThreadProcessId(interopHelper.Handle, IntPtr.Zero);
    var currentForegroundWindow = GetForegroundWindow();
    var currentForegroundWindowThreadId = GetWindowThreadProcessId(currentForegroundWindow, IntPtr.Zero);
    
    AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, true);

    window.Show();
    window.Activate();
     // 去掉和其他线程的输入链接
    AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, false);
    // 用于踢掉其他的在上层的窗口
            window.Topmost = true;
            window.Topmost = false;
}
技术图片

 

以上是关于WPF 让窗口激活作为前台最上层窗口的方法的主要内容,如果未能解决你的问题,请参考以下文章

WPF 让窗口激活作为前台最上层窗口的方法

WPF 让窗口激活作为前台最上层窗口的方法

WPF 让窗口激活作为前台最上层窗口的方法

WPF 让窗口激活作为前台最上层窗口的方法

将后台窗口激活到前台的方法(使用AttachThreadInput和SetForegroundWindow两个API)

C# wpf 想让控件随着窗口大小变化而变化