0

I am using mutex to check one instance at the time. It works, but to be perfect I need to fix one bug. If program is in minimized state it will not restore it self after I click Ok. Any ideas?

This is in Program.cs :

if (process.Id != current.Id)
{
    SetForegroundWindow(process.MainWindowHandle);
    MessageBox.Show(new Form1 { TopMost = true }, "Application is already running!");

    Form1 f1 = new Form1();

    f1.WindowState = FormWindowState.Normal; // dont work
    f1.BringToFront();                       // dont work
    f1.Focus();                              // dont work

    break;
}
Karan
  • 12,059
  • 3
  • 24
  • 40
Vyt Autas
  • 61
  • 1
  • 7
  • Your f1 variable doesn't refer to your existing form, but rather a new one which is why setting properties on that variable have no effect. Are you trying to restore an existing form? If so you'll need to get a reference to it or use pinvoke if it's a form running in another instance of your application (which is what it sounds like) – pinkfloydx33 Jul 04 '18 at 08:44
  • The .NET Framework already knows how to do this automatically: https://stackoverflow.com/a/19326/17034 – Hans Passant Jul 04 '18 at 09:21
  • Yes I want to restore existing one. What is the easiest way to get reference to it? – Vyt Autas Jul 04 '18 at 11:51

1 Answers1

0

create an extension method:

using System.Runtime.InteropServices;

namespace System.Windows.Forms
{
    public static class Extensions
    {
        [DllImport( "user32.dll" )]
        private static extern int ShowWindow( IntPtr hWnd, uint Msg );

        private const uint SW_RESTORE = 0x09;

        public static void Restore( this Form form )
        {
            if (form.WindowState == FormWindowState.Minimized)
            {
                ShowWindow(form.Handle, SW_RESTORE);
            }
        }
    }
}

then use form.Restore() in your code.

Barr J
  • 10,636
  • 1
  • 28
  • 46