简体   繁体   中英

app to run only one instance in Windows and show form when main form is hide

i have a winform app via one form and need app to run only one instance in Windows i cant show form when this hide

i need a clear code for show my hidden form

in my form

this.Hide();

program.cs for run only one instance in Windows and focused on app and my question is how show main form when is hide() ???

        static void Main()
        {
         System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
         System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
         foreach (System.Diagnostics.Process p in myProcesses)
         {
            if (p.ProcessName == me.ProcessName)
               if (p.Id != me.Id)
               {   
                  SetForegroundWindow(p.MainWindowHandle);
                  SwitchToThisWindow(p.MainWindowHandle, true);
                  return;
               }
         }
       // continue normally
       }


[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SetForegroundWindow(IntPtr hwnd);

update: above code is fine for Foreground Window and minimize window ... its OK. My problem is how to show hidden form???

sorry for my English

i found solution. any code in NewInstanceHandler() run on old proccess :) i checked it via proccess ID. i think its best soultion.

for add Microsoft.VisualBasic.ApplicationServices right click on reference and checked Microsoft.VisualBasic .

using Microsoft.VisualBasic.ApplicationServices;

static Form1 MainForm;
[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    MainForm = new Form1();
    SingleInstanceApplication.Run(MainForm,  NewInstanceHandler);
}

public static void NewInstanceHandler(object sender, StartupNextInstanceEventArgs e)
{   
    // anything u need run on old instance
    // MainForm.Hide();
    MainForm.Show();
    MainForm.WindowState = FormWindowState.Normal;
    e.BringToForeground = true;
}


public class SingleInstanceApplication : WindowsFormsApplicationBase
{
     private SingleInstanceApplication()
     {
        base.IsSingleInstance = true;
     }
     public static void Run(Form f, StartupNextInstanceEventHandler startupHandler)
     {
        SingleInstanceApplication app = new SingleInstanceApplication();
        app.MainForm = f;
        app.StartupNextInstance += startupHandler;
        app.Run(new string[0]);
    }        
}

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