Created
July 28, 2017 00:39
-
-
Save jcorderodr/81072cfbda7e4cfcd9df9fb1f8995a5c to your computer and use it in GitHub Desktop.
Call External Windows from C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Diagnostics; | |
| using System.Linq; | |
| using System.Runtime.InteropServices; | |
| using System.Windows.Forms; | |
| using MainApplication.Service; | |
| namespace MainApplication | |
| { | |
| static class Program | |
| { | |
| private static Form _frm; | |
| private const string AppNameExe = "AppNameTest.exe"; | |
| /// <summary> | |
| /// The main entry point for the application. | |
| /// </summary> | |
| [STAThread] | |
| static void Main() | |
| { | |
| var prc = Process.GetProcessesByName(AppNameExe).FirstOrDefault(); | |
| if (prc != null && AlreadyRunning(prc)) | |
| { | |
| //What to do if its running? | |
| return; | |
| } | |
| Application.EnableVisualStyles(); | |
| Application.SetCompatibleTextRenderingDefault(false); | |
| _frm = new Form(); | |
| Application.Run(_frm); | |
| } | |
| #region App Runner | |
| [DllImport("user32.dll")] | |
| private static extern bool SetForegroundWindow(IntPtr hWnd); | |
| [DllImport("user32.dll")] | |
| private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); | |
| [DllImport("user32.dll")] | |
| private static extern bool IsIconic(IntPtr hWnd); | |
| /// <summary> | |
| /// Checks if a process is already running. If yes, sets focus. | |
| /// </summary> | |
| /// <param name="process"></param> | |
| /// <returns></returns> | |
| public static bool AlreadyRunning(Process process) | |
| { | |
| const int SW_HIDE = 0; | |
| const int SW_SHOWNORMAL = 1; | |
| const int SW_SHOWMINIMIZED = 2; | |
| const int SW_SHOWMAXIMIZED = 3; | |
| const int SW_SHOWNOACTIVATE = 4; | |
| const int SW_RESTORE = 9; | |
| const int SW_SHOWDEFAULT = 10; | |
| IntPtr hWnd = process.MainWindowHandle; | |
| // if iconic, we need to restore the window | |
| if (IsIconic(hWnd)) | |
| { | |
| ShowWindowAsync(hWnd, SW_RESTORE); | |
| } | |
| // bring it to the foreground | |
| SetForegroundWindow(hWnd); | |
| // always | |
| return true; | |
| } | |
| #endregion | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment