WPF应用跟随桌面切换

有些程序可能设计的初衷是全局使用,但是实际使用过程中会涉及到切换桌面

假设程序启动在桌面1,当前工作在桌面2,当程序被使用激活时,会自动跳回桌面1

显然这个不符合全局使用的初衷

现在我们来解决

首先我们的主程序窗口要取消焦点获取:

Focusable = false;

然后在窗口加载完的时候加上:

IntPtr handle = new WindowInteropHelper(this).Handle;
var temp = GetWindowLongPtr(handle , GetWindowLongFields.GWL_EXSTYLE);
SetWindowLongPtr(handle, GetWindowLongFields.GWL_EXSTYLE, new IntPtr((int)temp | 0x08000000));

这里用到的两个User32的API需要导入:

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetWindowLongPtr(IntPtr hWnd, GetWindowLongFields nIndex);

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetWindowLongPtr(IntPtr hWnd, GetWindowLongFields nIndex, IntPtr dwNewLong);

还有一个枚举:

public enum GetWindowLongFields
{
    GWL_WNDPROC = -4,
    GWL_HINSTANCE = -6,
    GWL_HWNDPARENT = -8,
    GWL_STYLE = -16,
    GWL_EXSTYLE = -20,
    GWL_USERDATA = -21,
    GWL_ID = -12,
}

至此,无论你的桌面怎么切换,你的程序就会始终跟随你的桌面了

posted @ 2026-08-10 14:47  Poetindusk  阅读(1)  评论(0)    收藏  举报