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

时间:2013-01-08 07:43:48

标签: wpf window focus

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

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

我尝试使用MainView.ShowActivated="False",但它没有用。 我是否需要按照here或什么来使用HwndSource?

我在Kent的帮助下使用的代码(仅在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);
                }
            }

4 个答案:

答案 0 :(得分:5)

在我的recent blog post中,我使用SetWindowPos将窗口带到z顺序的前面而不给它焦点。我不相信WPF有一个内置的方法,可以在没有p / invoke的情况下实现相同的目标。

答案 1 :(得分:3)

我有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
        }
    }
}

答案 2 :(得分:3)

让我们调用您想要显示的窗口而不关注焦点:YourWindow。添加以下代码:

  

YourWindow.ShowActivted = false;

     

YourWindow.Owner = TheOtherWindowThatWillStilHaveFocus;

第一行你也可以从Xaml设置。

答案 3 :(得分:0)

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

相关问题