Search code examples
wpfnotifyicon

Show window after double click in notify icon (after minimize to tray)


I want to use in my wpf aplication notify icon (with .dll library in project http://www.codeproject.com/Articles/36468/WPF-NotifyIcon).

But I don't know, how to show my window (after minimize to tray) by double click in tray icon.

I declared new command

namespace MyBasicFlyffKeystroke
{
    class ShowWindowCommand : ICommand
    {
        public void Execute(object parameter)
        {
            Window1 window = new Window1();
            window.Show();
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;
    }
}

And I used it in my window1.xaml file:

<tb:TaskbarIcon x:Name="notifyIcon" IconSource="icon.ico" ToolTipText="MyBasicFlyffKeystroke" 
    DoubleClickCommand="{StaticResource ShowWindow}">                    
</tb:TaskbarIcon>

and

<Grid.Resources>
    <my:ShowWindowCommand x:Key="ShowWindow" />
</Grid.Resources>

But after double clicking open new instance with Window1... Is any metod here?

Best regards, Dagna


Solution

  • Try add an event handler for window messages

    Command

    namespace MyBasicFlyffKeystroke
    {
        class ShowWindowCommand : ICommand
        {
            public void Execute(object parameter)
            {
                // Broadcast isn't a good idea but work...
                NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);
            }
    
            public bool CanExecute(object parameter)
            {
                return true;
            }
    
            public event EventHandler CanExecuteChanged;
        }
    }
    

    In Window1

    protected override void OnSourceInitialized(EventArgs e) {
        base.OnSourceInitialized(e);
        HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
        source.AddHook(WndProc);
    }
    
    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {
        if (msg == NativeMethods.WM_SHOWME) {
            WindowState = WindowState.Normal;
        }
        return IntPtr.Zero;
    }
    

    And in NativeMethods (UPDATED)

    public static readonly int HWND_BROADCAST = 0xffff;
    public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");
    
    [DllImport("user32.dll")]
    public static extern int RegisterWindowMessage(string message);
    
    [DllImport("user32.dll")]
    public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);