Click here to Skip to main content
15,936,758 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
I am trying to create a form with a button that when click will search for calc.exe, if its running, it positiones the calc window to 0,0 top left corner of the screen. if its not running, it launces calc and then positions it to 0,0 top left of screen. Im learning C# so please comment the heck out of it

This just like a pseudo code. You can solve it by using the following steps.

HWND iHandle = FindWindow(null, "Calculator");
            if (iHandle != IntPtr.Zero)
                Rectangle rect = new Rectangle();
                GetWindowRect(iHandle, ref rect);
                // set the position as required 
               Process runExe = new Process();
               runExe.StartInfo.FileName = "calc.exe";
               // set the position as required 
Share this answer
The running "calc.exe" process can be started using System.Diagnostics.Process.Start. This is either an instance method, so you should have an instance of System.Diagnostics.Process previously created from a constructor, or it is a static method returning such instance. Keep this reference to the Process instance for future use.

You can try to find an instance of the running process using the method(s) System.Diagnostics.Process.GetProcessesByName.

This way, you got an instance of the external running process, no matter if it was started before or you started it. Get its main window handle using Process.MainWindowHandle. See the description of this method: you will need to catch the specified exceptions and check that the returned handle is not System.IntPtr.Zero. It would indicate that a process is terminated or not yet ready, or the main windows was not yet created. If the process is not terminated, you may need to call this property again until you get a main window.

Please see:[^].

When you get the main window handle, move the the window using raw Windows API , P/Invoked.
This is the ready-to-use P/Invoked code:[^].

Raw API:[^]; see other window-related API in the menu on left.

See also:[^],[^].

A useful CodeProject article: Essential P/Invoke[^].

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900