I. Three SDK functions:
WinExec, ShellExecute, and CreateProcess can meet the requirements for calling other programs. Among them, WinExec is the simplest, ShellExecute is more flexible than WinExec, and CreateProcess is the most complex.
Two WinExec parameters: the first one specifies the path, and the last one specifies the display mode.
ShellExecute can specify a working directory, and you can also find file associations to directly open applications that do not need to be loaded with the file association. ShellExecute can also open webpages and start relevant email Association sending emails.
CreateProcess has a total of ten parameters, but most of them can be replaced by NULL. It can specify the process's security attributes, Inheritance Information, class priority, and so on. If we want to get enough information about the new process and control the detailed attributes of the new process, we need to use the CreateProcess function to achieve this purpose.
1. winexec (String lpCmdLine, Long nCmdShow );
Parameter description:
| Parameters |
Type and description |
| LpCmdLine |
String, containing the command line to be executed |
| NCmdShow |
Long: Specifies a command for visibility in the window. Use any of the following Constants |
| SW_HIDE |
Hide the window. The activity status gives a window |
| SW_MINIMIZE |
Minimizes the window, and the activity status gives a window |
| SW_RESTORE |
Displays a window with the original size and position, and enables it to enter the active status. |
| SW_SHOW |
Displays a window with the current size and position, and enables it to enter the active status. |
| SW_SHOWMAXIMIZED |
Maximize the window and activate it |
| SW_SHOWMINIMIZED |
Minimize the window and activate it |
| SW_SHOWMINNOACTIVE |
Minimizes a window without changing the activity window. |
| SW_SHOWNA |
Displays a window with the current size and position without changing the activity window. |
| SW_SHOWNOACTIVATE |
Displays a window with the nearest size and position without changing the activity window. |
| SW_SHOWNORMAL |
Same as SW_RESTORE |
Example: winexec ("c: \ a.txt", SW_SHOW );
2. ShellExecute
| Parameters |
Type and description |
| Hwnd |
Long: Specifies the handle of a window. Sometimes, it is necessary for a windows program to display a message box before creating its own main window. |
| LpOperation |
String, specify the String "open" to open the lpFlie document, or specify "Print" to Print it |
| LpFile |
String, you want to use the associated program to print or open a program name or file name |
| LpParameters |
String. If lpszFlie is an executable file, the String contains the parameters passed to the execution program. |
| LpDirectory |
String, the complete path to be used |
| NShowCmd |
Long defines how to display the constant value of the Startup Program. See the table above. |
The usage is as follows:
Example: ShellExecute (Handle, ''open'', PChar (''c: \ test \ readme.txt ''), nil, nil, SW_SHOW );
ShellExecute (NULL, "open", "C: // Test.txt", NULL, NULL, SW_SHOWNORMAL); // open the C:/Test.txt File
ShellExecute (NULL, "open", "http://www.bkjia.com",/NULL, NULL, SW_SHOWNORMAL); // open the webpage www.2cto.com
ShellExecute (NULL, "explore", "D: // C ++", NULL, NULL, SW_SHOWNORMAL); // open the Directory D:/C ++
ShellExecute (NULL, "print", "C: // Test.txt", NULL, NULL, SW_HIDE); // print the file C:/Test.txt
3. CreateProcess
Parameter type and description lpApplicationNameString, the name of the application to be executed. It can be set to vbNullString. In this case, the application name should contain lpCommandLineString at the beginning of the lpCommandLine parameter and the command line to be executed. You can use the GetCommandLine function to obtain the command line used by a process. Windows tries its best to find the execution file in the following search order:
(1) directory containing the execution file of the parent process
(2) Current Directory of the parent process
(3) system directory returned by GetSystemDirectory
(4) windows NT: 16-bit system directory only
(5) Windows directory returned by GetWindowDirectory
(6) Specify the lpProcessAttributesSECURITY_ATTRIBUTES directory specified by the PATH environment variable, specify a SECURITY_ATTRIBUTES structure, or pass the zero value (declare the parameter As ByVal As Long, and pass the zero value) -- indicates that the default descriptor that cannot be inherited is used. This parameter defines the process's security feature lpThreadAttributesSECURITY_ATTRIBUTES, specifies a SECURITY_ATTRIBUTES structure, or transmits a zero value (declare the parameter As ByVal As Long, and pass the zero value) -- indicates that the default descriptor that cannot be inherited is used. This parameter defines the security feature bInheritHandlesLong of the main thread of the process. TRUE indicates that all handles in the current process are allowed to inherit dwCreationFlagsLong from the newly created sub-process, one or more of the following constants from the API32.TXT file are prefixed with CREATE _. The following code is used by VB programmers: CREATE_SEPARATE_WOW_VDM (applicable only to NT) forces CREATE_SHARED_WOW_VDM (applicable only to NT) to run a 16-bit Windows application in its own memory space) when a 16-bit Windows application is started, it is forced to run create_suincluded in the shared 16-bit Virtual Machine (VM) to immediately suspend the new process. Unless the ResumeThread function is called, it will not resume operation or may be one of the following constants, it is used to specify the priority. New IDLE_PRIORITY_CLASS processes should have a very low priority-they can only run when the system is idle. The basic value is 4HIGH_PRIORITY_CLASS. The new process has a very high priority, which takes precedence over most applications. The basic value is 13. Avoid using the NORMAL_PRIORITY_CLASS standard priority. If the process is on the foreground, the basic value is 9. If the process is on the background, the priority value is 7. Do not use REALTIME_PRIORITY_CLASSlpEnvironmentAny in VB, the pointer to an environment block (the first character of the Environment buffer, or the address of the Environment block) is the lpCurrentDriectoryString, the current directory path of the new process. When calling a function, you can use vbNullString to specify the current directory lpStartupInfoSTARTUPINFO and a STARTUPINFO structure, which contains the additional information lpProcessInformation used during process creation.
PROCESS_INFORMATION, which is used to hold the process and thread identifier of the new process. In most cases, once this function returns, the parent Application Closes two handles.
Ii. How to judge WinExec, ShellExecute, CreateProcess, and return values
There are three API functions that can run the executable files WinExec, ShellExecute, and CreateProcess. Because of its complexity, CreateProcess is rarely used.
WinExec mainly runs the EXE file.
(1) function prototype: UINT Win Exec (LPCSTR lpCmdLine, UINT uCmdShow );
(2) parameters:
LpCmdLine: A string pointing to an empty ending string containing the command line of the application to be executed (the file name is added with an optional parameter ).
UCmdShow: defines how Windows application Windows are displayed, and provides the value of the wShowWindow member of STARTUPINFO for the CreateProcess function.
(3) return value:
If the function is successfully called, the return value is greater than 31. If the function call fails, the return value is one of the following:
① 0: The system memory or resources are used up.
② ERROR_BAD_FORMAT: the EXE file is invalid (non-Win32.EXE or. EXE image error ).
③ ERROR_FILE_NOT_FOUND: the specified file is not found.
④ ERROR_PATH_NOT_FOUND: the specified path is not found.
Microsoft considers WinExec obsolete, but in many cases, simple WinExec functions are still the best way to run new programs. Simply passing the command line that acts as the first parameter also requires deciding how to display the second parameter of the Program (which may ignore it. Generally, set it to SW_SHOW. You can also try SW_MINIMIZED or SW_MAXIMIZED. WinExec does not allow all options obtained using CreateProcess, but it is indeed simple.
ShellExecute can run not only EXE files, but also associated files.
1. Standard usage
The meanings of the parameters and prototype of the ShellExecute Function are as follows:
HINSTANCE ShellExecute (HWND hwnd, LPCTSTR lpOperation, lpFile, lptstr lpParameters, lpDirectory, INT nShowCmd );
● HWnd: Specifies the parent window handle. When an error occurs during a function call, it is used as the parent window of the Windows message window. For example, you can set it to the Application Main Window Handle, that is, Application. Handle, or desktop window Handle (obtained using the GetDesktopWindow function ).
● LpOperation: used to specify the operation to be performed. The "open" operation indicates that the program specified by the FileName parameter is executed, or the file or folder specified by the FileName parameter is opened. The "print" operation indicates that the file specified by the FileName parameter is printed; the "Browse e" operation indicates browsing the folder specified by the FileName parameter. If the parameter is set to nil, the default operation "open" is executed ".
● LpFileName: used to specify the name of the file to be opened, the name of the program file to be executed, or the name of the folder to be browsed.
● LpParameters: If the FileName parameter is an executable program, this parameter specifies the command line parameter. Otherwise, this parameter should be nil or PChar (0 ).
● LpDirectory: used to specify the default directory.
● LpShowCmd: If the FileName parameter is an executable program, this parameter specifies the initial display mode of the program window; otherwise, this parameter should be set to 0.
Return Value:
[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Include <windows. h>
# Include <shellapi. h>
Int main (void)
{
HINSTANCE hNewExe = ShellExecuteA (NULL, "open", "d :\\ tese. log", NULL, NULL, SW_SHOW );
If (DWORD) hNewExe <= 32)
{
Printf ("return value: % d \ n", (DWORD) hNewExe );
}
Else
{
Printf ("successed! \ N ");
}
Printf ("GetLastError: % d \ n", GetLastError ());
System ("pause ");
Return 1;
}
If the "D: \ test. log" file does not exist, the execution result is as follows:
If a function execution error occurs, GetLastError () may not capture the error code, for example, when "d: \ tese. log file exists. When Notepad "notepad.exe" is named as another name:
The return values of the other two functions are not listed.
2. Special usage
1) if you set the FileName parameter to the "http:" protocol format, this function will open the default browser and link to the specified URL address. If multiple browsers are installed on your machine, the function determines which browser to start based on the settings of the http Handler (Protocols Handler) in Windows 9x/NT Registry.
Format 1: http: // website domain name. Example: ShellExecute (handle, "open", "http://www.neu.edu.cn", nil, nil, SW_SHOWNORMAL );
Format 2: http: // website domain name/Webpage file name. Example: ShellExecute (handle, "open", "http://www.neu.edu.cn/default.htm", nil, nil, SW_SHOWNORMAL );
2) If you set the FileName parameter to the "mailto:" protocol format, this function starts the default mail client program, such as Microsoft Outlook (including Microsoft Outlook Express) or Netscape Messanger. If multiple email client programs are installed on your machine, this function determines which email client program to start based on the settings of the mailto protocol handler in the Windows 9x/NT Registry.
Format 1: mailto: for example: ShellExecute (handle, "open", "mailto:", nil, nil, SW_SHOWNORMAL); open the new mail window.
Format 2: mailto: User Account @ mail server address such as: ShellExecute (handle, "open", "mailto: who@mail.neu.edu.cn", nil, nil, SW_SHOWNORMAL );
Open the new email window and enter the recipient address automatically. If multiple recipient addresses are specified, the recipient addresses must be separated by semicolons or commas (, the same below)
Example: ShellExecute (this-> m_hWnd, "open", "mailto: nishinapp@yahoo.com", "", "", SW_SHOW );
Format 3: mailto: User Account @ email server address? Subject = Email subject & body = Email body
Example: ShellExecute (handle, "open", "mailto: who@mail.neu.edu.cn? Subject = Hello & Body = This is a test ", nil, nil, SW_SHOWNORMAL );
Open the new email window and enter the recipient address, subject, and body. If the mail body contains multiple lines of text, you must add the line feed escape character % 0a between each line of text.
Example (delphi ):
Call c: Project1.exe in an application;
ShellExecute (handle, 'open', 'c: Project1.exe ', 'string content', nil, SW_SHOWNORMAL );
In project1.exe, you can call:
Procedure TForm1.FormCreate (Sender: TObject );
Var I: integer;
Begin
For I: = 1 to paramcount do
If ParamStr (I) <> ''then showmessage (ParamStr (I ));
End;
The last parameter specifies the visibility command for the window. Use any of the following Constants
SW_HIDE hides the window, and the activity status gives a window
SW_MINIMIZE minimizes the window, and the active status gives a window
SW_RESTORE displays a window with the original size and position, and enables it to enter the active status.
SW_SHOW displays a window with the current size and position, and enables it to enter the active status.
SW_SHOWMAXIMIZED: Maximize the window and activate it.
SW_SHOWMINIMIZED minimizes the window and activates it.
SW_SHOWMINNOACTIVE minimizes a window without changing the activity window.
SW_SHOWNA displays a window with the current size and position without changing the activity window.
SW_SHOWNOACTIVATE displays a window with the latest size and position without changing the activity window.
SW_SHOWNORMAL is the same as SW_RESTORE.
3. Go to ShellExecute Translator: Xu Jingzhou (Original: Nishant S)
Q: How to open an application? As you can see, I have not passed the complete path of the program.
ShellExecute (this-> m_hWnd, "open", "calc.exe", "", "", SW_SHOW );
Or ShellExecute (this-> m_hWnd, "open", "notepad.exe", "c: \ MyLog. log", "", SW_SHOW );
Q: How do I open a file related to the same system program?
ShellExecute (this-> m_hWnd, "open", "c: \ abc.txt", "", "", SW_SHOW );
Q: How to open a webpage?
ShellExecute (this-> m_hWnd, "open", "http://www.bkjia.com", "", "", SW_SHOW );
Q: How to activate related programs and send emails?
ShellExecute (this-> m_hWnd, "open", "mailto: nishinapp@yahoo.com", "", "SW_SHOW );
Q: How do I print documents with a system printer?
ShellExecute (this-> m_hWnd, "print", "c: \ abc.txt", "", "", SW_HIDE );
Q: How can I use the system search function to find a specified file?
ShellExecute (m_hWnd, "find", "d: \ nish", NULL, NULL, SW_SHOW );
Q: How do I start a program until it finishes running?
SHELLEXECUTEINFO ShExecInfo = {0 };
ShExecInfo. cbSize = sizeof (SHELLEXECUTEINFO );
ShExecInfo. fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo. hwnd = NULL;
ShExecInfo. lpVerb = NULL;
ShExecInfo. lpFile = "c: \ MyProgram.exe ";
ShExecInfo. lpParameters = "";
ShExecInfo. lpDirectory = NULL;
ShExecInfo. nShow = SW_SHOW;
ShExecInfo. hInstApp = NULL;
ShellExecuteEx (& ShExecInfo );
WaitForSingleObject (ShExecInfo. hProcess, INFINITE );
Or:
PROCESS_INFORMATION ProcessInfo;
STARTUPINFO StartupInfo; // This is an [in] parameter
ZeroMemory (& StartupInfo, sizeof (StartupInfo ));
StartupInfo. cb = sizeof (StartupInfo); // Only compulsory field
If (CreateProcess ("c: \ winnt \ notepad.exe", NULL, FALSE, 0, NULL, NULL, & StartupInfo, & ProcessInfo ))
{
WaitForSingleObject (ProcessInfo. hProcess, INFINITE );
CloseHandle (ProcessInfo. hThread );
CloseHandle (ProcessInfo. hProcess );
}
Else
{
MessageBox ("The process cocould not be started ...");
}
Q: How do I display attributes of a file or folder?
SHELLEXECUTEINFO ShExecInfo = {0 };
ShExecInfo. cbSize = sizeof (SHELLEXECUTEINFO );
ShExecInfo. fMask = SEE_MASK_INVOKEIDLIST;
ShExecInfo. hwnd = NULL;
ShExecInfo. lpVerb = "properties ";
ShExecInfo. lpFile = "c: \"; // can be a file as well
ShExecInfo. lpParameters = "";
ShExecInfo. lpDirectory = NULL;
ShExecInfo. nShow = SW_SHOW;
ShExecInfo. hInstApp = NULL;
ShellExecuteEx (& ShExecInfo );
Use the CreateProcess command
(1) function prototype:
BOOL CreateProcess (
Lptstr lpApplicationName,
LPTSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
Maid directory,
LPSTARTUPINFO lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
);
(2) parameters:
LpApplicationName: point to an empty string that specifies the module to be executed.
LpCommandLine: point to an empty string that defines the command line to be executed.
LpProcessAttributes: points to a SECURITY_ATTRIBUTES structure, which determines whether the returned handle can be inherited by the quilt process.
LpThreadAttributes: points to a SECURITY_ATTRIBUTES structure, which determines whether the returned handle can be inherited by the quilt process.
BInheritHandles: indicates whether the new process inherits the handle from the called process.
DwCreationFlags: defines the control priority class and additional identifier for Process Creation.
LpEnvironment: point to the Environment block of a new process.
LpCurrentDirectory: point to an empty string that defines the current drive and directory of the child process.
LpStartupInfo: points to a STARTUPINFO structure, which defines how the new process's main window will be displayed.
LpProcessInformation: point to the PROCESS_INFORMATION structure, which accepts the representation information about the new process.
(3) return value:
If the function call is successful, the return value is not 0. If the function call fails, the return value is 0.
In the preceding parameters, the lpStartupInfo parameter is the STARTUPINFO structure. You can set the title of the console, the initial size and position of the new window, and redirect standard input and output. Most of these data items can be ignored by new programs. You can specify a flag in the struct that indicates the data segment to be set. Sometimes, if you do not want to set any information, you must also pass a valid pointer to the null structure (make sure to set the size to cb, and set the dwFlags member to 0 ). The lpProcessInformation parameter returns the process and thread handle, including the process and thread ID. These handles have the access specified in the lpProcessAttributes and lpThreadAttributes parameters.
Note that some parameters for CreateProcess are specific to the console application, while other parameters are useful to various applications. In most cases, you do not have to enter the STARTUPINFO structure, but you must provide it anyway. The return value is Boolean, and the returned value that is really interest occurs in the structure transmitted as a parameter (PROCESS_INFORMATION ). CreateProcess returns the process ID and its handle in the structure, as well as the initial thread ID and its handle. You can send an ID to another process or use a handle to control the new process.
The ShellExecute and WinExec commands are used for simple jobs. To completely control a new process, you must call CreateProcess.
Bytes ---------------------------------------------------------------------------------------------------------
Iii. Notes
1. Define the header file
The following two header files must be defined in the header file stdafx. h:
# Include <shlobj. h> // you can replace it with windows. h.
# Include <shellapi. h>
If the header file # include <windows. h> you do not need to define # include <shlobj. h> now, "windows. h "not only contains" shellapi. h ", it also defines many data types, if not, shellapi. h itself will fail.
From the column lanbing510