Question

J'ai utilisé un mutex pour exécuter un programme à instance unique et je souhaite maintenant que la fenêtre soit agrandie si elle est actuellement réduite lorsque l'utilisateur rouvre l'application.

Voici le code que j'ai actuellement dans mon fichier Program.cs :

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());

    }
}
Était-ce utile?

La solution

Vous recherchez le ShowWindow fonction et le SW_MAXIMIZE drapeau.

En C#, la déclaration P/Invoke ressemblerait à ceci :

[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;

Ajoutez-le à votre code ici :

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


Si vous souhaitez réellement tester si la fenêtre est réduite avant de la maximiser, vous pouvez utiliser la méthode à l'ancienne IsIconic fonction:

[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);
   }
}

Si vous souhaitez simplement activer la fenêtre (plutôt que de la maximiser), utilisez le SW_SHOW valeur (5) au lieu de SW_MAXIMIZE.Cela le restaurera à son état précédent, avant qu'il ne soit réduit.

Autres conseils

Je voudrais suggérer une solution purement .NET (c'est-à-dire sans dépendance du système d'exploitation).

programme.cs

static class Program
{
    private static volatile bool _exitProcess;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        bool createdNew;
        var showMeEventHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "MyApp.ShowMe", out createdNew);

        if (createdNew)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var form = new Form1();
            new Thread(() =>
            {
                while (!_exitProcess)
                {
                    showMeEventHandle.WaitOne(-1);
                    if (!_exitProcess)
                    {
                        if (form.InvokeRequired)
                        {
                            form.BeginInvoke((MethodInvoker)form.BringFormToFront);
                        }
                        else
                        {
                            form.BringFormToFront();
                        }
                    }
                }
            }).Start();

            Application.Run(form);
        }

        _exitProcess = true;
        showMeEventHandle.Set();

        showMeEventHandle.Close();
    }
}

extmethods.cons

public static class ExtMethods
{
    public static void BringFormToFront(this Form form)
    {
        form.WindowState = FormWindowState.Normal;
        form.ShowInTaskbar = true;
        form.Show();
        form.Activate();
    }
}

form1.cs

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.BringFormToFront();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            Hide();
        }
    }

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top