How do I get the form from MainWindowHandle?

I have a program that only allows one instance to run. I am using this code

bool createdNew = true;
using(Mutex mutex = new Mutex(true, "MobilePOSServer", out createdNew))
{
    if(createdNew)
    {

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
    else
    {
        Process current = Process.GetCurrentProcess();
        foreach(Process proc in Process.GetProcessesByName(current.ProcessName))
        {
            if(proc.Id != current.Id)
            {
                SetForegroundWindow(proc.MainWindowHandle);
            }
        }
    }
}

      

What I want to do is process the command line arguments to call some start and stop methods in my winform MainForm. I can start from the beginning. But starting the application from a new command prompt window and trying to call the method don't work. I can force the window to come out to the front. Is there a way to get my form from a handle?

Or is there a better way to do this?

+1


a source to share


3 answers


This is what you are looking for:



Single instance application passing command line arguments

+2


a source


You won't be able to get a link to the form itself, no - this object exists in a different process.



If you want to be able to control another process, it will need to open some kind of "remote access" (where "remote" in this case means "out of the process" and not "on another machine" "). This could be via remote. NET, WCF, or your own simple protocol based on sockets, named pipes, etc. However, this is likely to hurt a little - so weigh how much you really want this feature before you start putting too much work into it.

+2


a source


If the methods you want to execute on the remote application are simple, you can also use SendMessage / PostMessage to send a Windows message to another application and trigger the operations to be performed.

If you really need to interact more with another instance than with a simple trigger, I would have to go with John, and I would opt for WCF with named pipes. According to him, this will be a more complex decision, and you should think about how important this function is for the application.

+1


a source







All Articles