简体   繁体   中英

Maximize WPF application from the taskbar using another application instance and Caliburn.Micro

I'm writing a WPF application in Caliburn.Micro that needs to minimize to the Taskbar when closed. That part is easy using Hardcodet TaskbarIcon control. This app should also be a single instance application which I'm using a global mutex for.

The problem I'm running into is: I want to maximize the current instance from the taskbar if another instance of the application is trying to start. So check the mutex, if it cant get a lock, find the other instance and maximize it from the taskbar and shut itself down. I can't do a user32.dll ShowWindow because there is no window handle to grab when its in the taskbar.

I ideally want to do a SendMessage from the opening instance to the existing instance and tell it to maximize itself, but I cant figure out how to handle a SendMessage event using Caliburn.Micro. Unfortunately, this is the only solution I can think of and I can't figure out how to do it.

Have a look at PostMessage

Here is a great example of someone using PostMessage to do exactly what you're talking about.

Basically, you use PostMessage to broadcast a custom message:

NativeMethods.PostMessage(
                (IntPtr)NativeMethods.HWND_BROADCAST,
                NativeMethods.WM_SHOWME,
                IntPtr.Zero,
                IntPtr.Zero);

Then you override WndProc to receive the message:

protected override void WndProc(ref Message m) 
{
    if(m.Msg == NativeMethods.WM_SHOWME) 
    {
        // code here to maximize 
    }
    base.WndProc(ref m);
}

Note that you need to register your custom message and extern in the needed win32 stuff:

internal class NativeMethods 
{
    public const int HWND_BROADCAST = 0xffff;
    public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");
    [DllImport("user32")]
    public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
    [DllImport("user32")]
    public static extern int RegisterWindowMessage(string message);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM