如何在WPF中将窗口粘贴到桌面顶部?

问题描述 投票:-2回答:1

我有一个类似码头的应用程序(网格中的一些图像,如小部件),只有当桌面是当前的前台窗口时,才需要停留在桌面上。

我当前正在使用在这里和那里收集的非托管代码来在前景窗口更改时获取前景窗口的名称。 ActiveWindowTitle() == null时,我使用Topmost将我的应用程序窗口置于最前面,因为切换到桌面时,前景窗口为空。问题是其他应用程序有时也会返回空窗口。

如何确定当前的前台窗口是桌面而不是其他程序?

    delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
    private static WinEventDelegate stickyDelegate = null;

    [DllImport("user32.dll")]
    static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);

    private const uint WINEVENT_OUTOFCONTEXT = 0;
    private const uint EVENT_SYSTEM_FOREGROUND = 3;

    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

    public static void ActivateStickToDesktop()
    {
        stickyDelegate = new WinEventDelegate(WinEventProc);
        IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, stickyDelegate, 0, 0, WINEVENT_OUTOFCONTEXT);
    }

    private static string GetActiveWindowTitle()
    {
        const int nChars = 256;
        IntPtr handle = IntPtr.Zero;
        StringBuilder Buff = new StringBuilder(nChars);
        handle = GetForegroundWindow();

        if (GetWindowText(handle, Buff, nChars) > 0)
        {
            return Buff.ToString();
        }
        return null;
    }

    public static void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
    {
        activeWindowName = GetActiveWindowTitle();
        Console.WriteLine("Current active window name: " + activeWindowName);

        if(string.IsNullOrEmpty(activeWindowName))
        {
            AppWindow.Topmost = true;
        } else
        {
            AppWindow.Topmost = false;
            SendToBottom(AppWindow);
        }

        Console.WriteLine("Is Topmost: " + AppWindow.Topmost);
    }
c# wpf pinvoke
1个回答
0
投票

要使窗口始终位于顶部,请进行我建议的更改。在Mainwindow.xaml中添加Topmost="True",也在mainwindow.xaml中添加Deactivated="Window_Deactivated"。在Mainwindow.xaml.cs内添加

private void Window_Deactivated(object sender, EventArgs e)
    {
        Window window = (Window)sender;
        window.Topmost = true;
    }

这在大多数情况下都适用

© www.soinside.com 2019 - 2024. All rights reserved.