deathrace
deathrace

Reputation: 1073

Activate WPF Window without losing focus on previous application/window

I have a WPF window in application which I Activate on some specific scenarios by calling MainView.Activate(); and MainView.BringIntoView(); method. it also sets focus on this 'MainView' window.

But my requirement is this window should not get Focus. i.e. my cursor should still remain on previous application(notepad,word etc..)

I tried using MainView.ShowActivated="False" but it didn't work. Do I need to use HwndSource as mentioned here or what?

Code I have used after Kent's help (Its working only if Window is minimized):

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

Upvotes: 5

Views: 8116

Answers (4)

Eli Dagan
Eli Dagan

Reputation: 848

Let's call the window that you want to show without focus: YourWindow. Add the following code:

YourWindow.ShowActivated = false;

YourWindow.Owner = TheOtherWindowThatWillStilHaveFocus;

First line you can also set from XAML.

Upvotes: 6

Kent Boogaart
Kent Boogaart

Reputation: 178660

In my recent blog post, I use SetWindowPos to bring a window to the front of the z-order without giving it focus. I don't believe WPF has an in-built means of achieving the same without p/invoke.

Upvotes: 5

ngm
ngm

Reputation: 309

I needed to solve a similar problem and got it to work by setting Window.ShowActivate=false and then using Window.Show rather than Window.Activate. Perhaps this will work for you. I have not yet needed to use BringIntoView because my window is newly created and appears on top of other windows by default.

Upvotes: 1

Mikhail
Mikhail

Reputation: 1028

I Have Win32 helper class for such situation here is listing for your case

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

Upvotes: 7

Related Questions