WPF 讓窗口激活做爲前臺最上層窗口的方法

原文參照林大佬的博客WPF 讓窗口激活做爲前臺最上層窗口的方法html

我只提供下,我使用的代碼post

[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;
}
相關文章
相關標籤/搜索