Mainly to deal with this need: the software is only allowed to be started once.
To convert this problem, you can describe it as follows: For a software, after starting a process, other processes are not allowed to be started. If the program is opened the second time, the window of the process that has been started is placed at the front end to display.
The C# winfrom application will first execute the code after it is started, so you need to start here. After startup, check whether there is a process with the same process name. If so, mention the window of that process to the front end and close yourself.
Usage: Change yours to this look:
static class Program { //windows API, used to display code [DllImport("")] [return: MarshalAs()] static extern bool SetForegroundWindow(IntPtr hWnd); /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { //Core code Process currProc = (); Process[] runningProc = (); //Check the rules to see if the process name is the same. You can flexibly customize it yourself, such as checking the username. var searchedProc=from a in runningProc where == select a; if (() > 1) { //Select the process with the same process name as the current process but with different ids Process firstProc = (a => != ); IntPtr firstProcWindow = ; SetForegroundWindow(firstProcWindow); (); } //-------end--------- (); (false); (new Form1()); } }
====================================================
Regarding the display and top of the window, there are 3 APIs involved in total.
//Display window
ShowWindow(hWnd, SW_NORMAL);
//Front end display
SetForegroundWindow(hWnd);
//The window is topped
SetWindowPos(hWnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
Among them, SetWindowPos is the most commonly used to set the position of the window. The most common purpose is to set the window to top, which is equivalent to =true in winform;
usage:
WinAPI: SetWindowPos - Change the position and status of the window
SetWindowPos(
hWnd: HWND; {window handle}
hWndInsertAfter: HWND; {Z order of windows}
X, Y: Integer; {position}
cx, cy: Integer; {size}
uFlags: UINT {Options}
): BOOL;
//hWndInsertAfter parameter optional value:
HWND_TOP = 0; {in the front}
HWND_BOTTOM = 1; {behind}
HWND_TOPMOST = HWND(-1); {In front, in front of any top window}
HWND_NOTOPMOST = HWND(-2); {In front, behind other top windows}
//uFlags parameter optional value:
SWP_NOSIZE = 1; {ignor cx, cy, keep size}
SWP_NOMOVE = 2; {ignor X and Y, do not change the position}
SWP_NOZORDER = 4; {ignor hWndInsertAfter, keep Z order}
SWP_NOREDRAW = 8; {No redraw}
SWP_NOACTIVATE = $10; {not activated}
SWP_FRAMECHANGED = $20; {Forced to send a WM_NCCALCSIZE message, usually it is only sent when the size is changed}
SWP_SHOWWINDOW = $40; {display window}
SWP_HIDEWINDOW = $80; {Hide window}
The above is the learning content of this article, I hope you like it.