Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximize window from the Main function?

I have used a mutex to run a single instance program, and now I want the window to become maximized if it is currently minimized when the user reopens the application.

Here is the code I currently have in my Program.cs file:

static class Program
{
    [DllImport("user32.dll")]
    public static extern bool SetForegroundWindow(IntPtr hWnd);

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        bool Ok = true;
        string ProductName = Application.ProductName;
        Mutex m = new Mutex(true, ProductName, out Ok);
        if (!Ok)
        {
            System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName(ProductName);
            SetForegroundWindow(p[0].MainWindowHandle);

    }
    else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());

    }
}
like image 462
Moslem7026 Avatar asked May 13 '11 09:05

Moslem7026


People also ask

What does it mean to maximize a window?

A feature of a graphics-based operating system that enlarges the window to the size of the screen. Contrast with minimize.


1 Answers

You're looking for the ShowWindow function and the SW_MAXIMIZE flag.

In C#, the P/Invoke declaration would look like this:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

private const int SW_MAXIMIZE = 3;

Add it to your code here:

if (!Ok)
{
   Process[] p = Process.GetProcessesByName(ProductName);
   SetForegroundWindow(p[0].MainWindowHandle);
   ShowWindow(p[0].MainWindowHandle, SW_MAXIMIZE);
}


If you actually want to test whether the window is minimized first before you maximize it, you can use the old-school IsIconic function:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsIconic(IntPtr hWnd);

// [...]

if (!Ok)
{
   Process[] p = Process.GetProcessesByName(ProductName);
   IntPtr hwndMain= p[0].MainWindowHandle;
   SetForegroundWindow(hwndMain);

   if (IsIconic(hwndMain))
   {
      ShowWindow(hwndMain, SW_MAXIMIZE);
   }
}

If you just want to activate the window (rather than maximize it), use the SW_SHOW value (5) instead of SW_MAXIMIZE. This will restore it to its previous state, before it was minimized.

like image 67
Cody Gray Avatar answered Sep 22 '22 05:09

Cody Gray