激活WPF窗口而不会失去对先前应用程序/窗口的关注

dea*_*ace 5 wpf focus window

我在应用程序中有一个WPF窗口,我可以通过调用MainView.Activate();MainView.BringIntoView();方法在某些特定情况下激活它。它还将焦点设置在此“ MainView”窗口上。

但我的要求是,该窗口不应获得焦点。即我的光标仍应保留在以前的应用程序(记事本,单词等)上。

我尝试使用,MainView.ShowActivated="False"但是没有用。我需要使用此处提到的HwndSource 还是什么?

我在肯特的帮助下使用过的代码(仅在最小化Window的情况下才起作用):

IntPtr HWND_TOPMOST = new IntPtr(-1);
            const short SWP_NOMOVE = 0X2;
            const short SWP_NOSIZE = 1;
            const short SWP_NOZORDER = 0X4;
            const int SWP_SHOWWINDOW = 0x0040;

            Process[] processes = Process.GetProcesses(".");

            foreach (var process in processes)
            {
                IntPtr handle = process.MainWindowHandle;
                if (handle != IntPtr.Zero)
                {
                    SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
                }
            }
Run Code Online (Sandbox Code Playgroud)

Mik*_*ail 6

我有针对这种情况的 Win32 助手类,这里列出了您的案例

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;

namespace your.namespace {
    public static class Win32 {
        public static void ShowWindowNoActive( Window window) {
            var hwnd = (HwndSource.FromVisual(window) as HwndSource).Handle;
            ShowWindow(hwnd, ShowWindowCommands.SW_SHOWNOACTIVATE);
        }

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, ShowWindowCommands nCmdShow);

        private enum ShowWindowCommands : int {
            SW_SHOWNOACTIVATE = 4
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ken*_*art 5

在我最近的博客文章中,我SetWindowPos经常将一个窗口置于z顺序的前面而不给其焦点。我不认为WPF具有内置的方法,无需p / invoke就可以实现相同的目标。

  • 博客链接已损坏。 (2认同)
  • @KentBoogaart链接再次断开 (2认同)

Eli*_*gan 5

让我们调用您想要在没有焦点的情况下显示的窗口:YourWindow。添加以下代码:

YourWindow.ShowActivated = false;

YourWindow.Owner = TheOtherWindowThatWillStilHaveFocus;

您也可以从 XAML 设置第一行。