5

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

但我的要求是这个窗口不应该得到焦点。即我的光标仍应保留在以前的应用程序上(记事本、word 等)

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

在肯特的帮助下我使用的代码(只有在窗口最小化时才有效):

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);
                }
            }
4

4 回答 4

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
        }
    }
}
于 2014-12-26T13:39:20.993 回答
5

在我最近的博客文章中,我习惯SetWindowPos将一个窗口放在 z 顺序的前面,而不给它焦点。我不相信 WPF 有在没有 p/invoke 的情况下实现相同的内置方法。

于 2013-01-08T08:44:44.943 回答
5

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

YourWindow.ShowActivated = false;

YourWindow.Owner = TheOtherWindowThatWillStilHaveFocus;

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

于 2016-08-29T13:50:44.703 回答
1

我需要解决一个类似的问题,并通过设置 Window.ShowActivate=false 然后使用 Window.Show 而不是 Window.Activate 来使其工作。也许这对你有用。我还不需要使用 BringIntoView,因为我的窗口是新创建的,并且默认显示在其他窗口的顶部。

于 2015-08-26T22:05:02.990 回答