Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activate WPF Window without losing focus on previous application/window

Tags:

focus

window

wpf

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);
                }
            }
like image 987
deathrace Avatar asked Jan 08 '13 07:01

deathrace


2 Answers

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
        }
    }
}
like image 98
Mikhail Avatar answered Sep 23 '22 23:09

Mikhail


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.

like image 28
Kent Boogaart Avatar answered Sep 25 '22 23:09

Kent Boogaart