Differences between ShellExecute, winexec, and CreateProcess

Source: Internet
Author: User
Tags microsoft outlook

ShellExecute
The function of ShellExecute is to run an external program (or open a registered file, open a directory, print a file, etc.) and control the external program.

Several API functions can implement these functions, but in most cases, ShellExecute is more used and not too complex.

The meanings of the parameters and prototype of the ShellExecute Function are as follows:

ShellExecute (

Hwnd, // parent window handle (such as null and handle)

Lpcstr lpoperation, // operation type (for example, "open") * double quotation marks must be added.

Lpstr lpfile, // file or path to be operated

Lpstr lpparameters, // when lpoperation is set to "too E", specify the parameter to be passed. It is usually set to null.

Lpstr lpdirectory, // specify the default directory, which is usually set to null

Int nshowcmd // specifies the mode in which the file is opened, which is usually maximized or minimized, and generally sw_shownormal.

)
Parameter description:
● 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 ).

● Operation: Specifies 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 ".

● Filename: 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.

● Parameters: If the filename parameter is an executable program, this parameter specifies the command line parameter; otherwise, this parameter should be nil or pchar (0 ).

● Directory: used to specify the default directory.

● Showcmd: 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.

If the ShellExecute Function is successfully called, the returned value is the instance handle of the executed program. If the returned value is smaller than 32, an error occurs.

The above is only the standard usage of the ShellExecute Function. The following describes its special usage.
Example:

// Call notepad

ShellExecute (null, "open", "Notepad. EXE", null, null, sw_shownormal );

2. Special usage

If you set the filename parameter to the "http:" protocol format, this function opens the default browser and links 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 ', null, null, sw_shownormal );

Format 2: http: // website domain name/Webpage file name.

Example: ShellExecute (handle, "open", http ://;

Www.neu.edu.cn/default.htm', null,null,

Sw_shownormal );

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:", null, null, sw_shownormal); opens the new mail window.

Format 2: mailto: User Account @ email server address

Example: ShellExecute (handle, "open", "mailto: who@mail.neu.edu.cn", null, null, sw_shownormal); opens a new mail window and automatically fills in the recipient address. If multiple recipient addresses are specified, the recipient addresses must be separated by semicolons or commas (, the same below ).

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); opens the new mail window and automatically fills in the recipient address, mail subject, and mail 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 is displayed to another window.

Sw_minimize minimizes the window, and the activity status is given to another 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.

 
 
 
Winexec
// Statement
Winexec (
Lpcmdline: lpcstr; {file name and parameter. If no path is specified, the system searches for the program directory/current directory/system32/Windows/PATH environment variable in the following order}
Ucmdshow: uint {startup option}
): Uint;

// Description: run the specified program.

// Return Value
More than 31 {successful call}
Equal to 0 {insufficient memory}
Error_file_not_found = 2; {file name error}
Error_path_not_found = 3; {path name error}
Error_bad_format = 11; {the EXE file is invalid}
(Refer to the findexecutable function)

// Parameter table:
Parameter type and description
Lpcmdline string, containing the command line to be executed
Ucmdshow long defines how to start the constant value of the program.
// Optional values of the ucmdshow parameter:
Sw_hide = 0; {hide, and the taskbar is not minimized.} sw_shownormal = 1; {display with the nearest size and position, activate}
Sw_normal = 1; {same as sw_shownormal}
Sw_showminimized = 2; {minimize, activate}
Sw_showmaximized = 3; {maximize, activate}
Sw_maximize = 3; {same as sw_showmaximized}
Sw_shownoactivate = 4; {display with the nearest size and position, not activated}
Sw_show = 5; {same as sw_shownormal}
Sw_minimize = 6; {minimized, not activated}
Sw_showminnoactive = 7; {same as sw_minimize}
Sw_showna = 8; {same as sw_shownoactivate}
Sw_restore = 9; {same as sw_shownormal}
Sw_showdefault = 10; {same as sw_shownormal}
Sw_max = 10; {same as sw_shownormal}
 
 
 

CreateProcess
Note:
The CreateProcess function of WIN32API is used to create a new process and its main thread. The new process runs the specified executable file.
Function prototype:
Bool CreateProcess
(
Lptstr lpapplicationname,
Lptstr lpcommandline,
Lpsecurity_attributes lpprocessattributes.
Lpsecurity_attributes lpthreadattributes,
Bool binherithandles,
DWORD dwcreationflags,
Lpvoid lpenvironment,
Maid directory,
Lpstartupinfo,
Lpprocess_information lpprocessinformation
);
Parameters:
Lpapplicationname: a string that points to a null end and is used to specify the executable module.
This string can make the absolute or relative path of the executable module. In the latter case, the function uses the current drive and directory to create the path of the executable module.
This parameter can be set to null. In this case, the name of the executable module must be at the beginning of the lpcommandline parameter and separated by a space character from the subsequent characters.
The specified module can be a Win32 application. If the appropriate subsystem is available on the current computer, it can also be another type of module (such as MS-DOS or OS/2 ).
In Windows NT, if the executable module is a 16-bit application, this parameter should be set to null because the name of the executable module should be specified in the lpcommandline parameter. A 16-bit application runs in a DOS virtual machine or Windows (WOW) on Win32.
Lpcommandline: Specifies the command line to be run at the end of a null value.
This parameter can be blank, so the function uses the string specified by the parameter as the command line of the program to be run.
If the lpapplicationname and lpcommandline parameters are not empty, the lpapplicationname parameter specifies the module to be run, and the lpcommandline parameter specifies the command line of the module to be run. The newly running process can use the getcommandline function to obtain the entire command line. The argc and argv parameters can be used in C language programs.
If the lpapplicationname parameter is null, the first space-separated element in the string specifies the executable module name. If the file name does not include the extension name, then .exe is assumed to be the default extension. If the file name ends with a dot (.) and no extension name exists, or the file name is included in the extension, .exe will not be added to the end. If the file name does not contain a path, Windows searches for the executable file in the following order:
1. The directory of the current application.
2. Parent process directory.
3. Windows 95: Windows System directory, which can be obtained using the getsystemdirectory function.
Windows NT: 32-bit Windows System directory. You can use the getsystemdirectory function to obtain the directory name system32.
4. in Windows NT: 16-bit Windows System directory. You cannot use the Win32 function to obtain this directory, but it will be searched. The directory name is system.
5. Windows directory. You can use the getwindowsdirectory function to obtain this directory.
6. The directory listed in the PATH environment variable.
If the created process is an application based on a MS-DOS or a 16-bit windows, the lpcommandline parameter should be an absolute path to an executable file name as the first element, this can make the 32-bit windows program work well, So setting the lpcommandline parameter is the strongest.
Lpprocessattributes: points to a security_attributes struct, which determines whether the returned handle can be inherited by the quilt process. If the lpprocessattributes parameter is null, the handle cannot be inherited.
In Windows NT, The lpsecuritydescriptor Member of the security_attributes structure specifies the security descriptor of the new process. If the parameter is blank, the new process uses the default security descriptor.
In Windows95, The lpsecuritydescriptor Member of the security_attributes structure is ignored.
Lpthreadattributes: points to a security_attributes struct, which determines whether the returned handle can be inherited by the quilt process. If the lpthreadattributes parameter is null, the handle cannot be inherited.
In Windows NT, The lpsecuritydescriptor Member of the security_attributes structure specifies the security descriptor of the main thread. If the parameter is blank, the main thread uses the default security descriptor.
In Windows95, The lpsecuritydescriptor Member of the security_attributes structure is ignored.
Binherithandles: indicates whether the new process inherits the handle from the called process. If the value of the parameter is true, every inherited open handle in the calling process inherits the quilt process. The inherited handle has the same value and access permissions as the original process.
Dwcreationflags: Specifies the appended identifier used to control priority classes and Process Creation. The following creation flag can be combined in any way except the method listed below.
Value: create_default_error_mode
Meaning: the new process does not inherit the Error Mode of the called process. The CreateProcess function allows the new process to replace the current default error mode. Applications can call the seterrormode function to set the current default error mode.
This flag is useful for Multithreaded Shell programs running in environments without hardware errors.
For the CreateProcess function, the default behavior is to inherit the caller's error mode for the new process. Set this flag to change the default processing method.
Value: create_new_console
Meaning: a new process uses a new console instead of inheriting the console of the parent process. This flag cannot be used with the detached_process flag.
Value: create_new_process_group
Meaning: the root process of a new process tree. All processes of the Process tree are the sub processes of the root process. The User Identifier of the new process tree is the same as that of the process, which is returned by the lpprocessinformation parameter. The generateconsolectrlevent function is often used in the process tree to send Ctrl + C or Ctrl + break signals to a group of console processes.
Value: create_separate_wow_vdm
Meaning: (only applicable to Windows NT) this flag is valid only when a 16-bit windows application is running. If set, the new process runs on a private virtual DOS host (vdm. In addition, by default, all 16-bit Windows applications run in the same shared vdm as threads. The advantage of running a 16-bit program separately is that the crash of an application will only end the running of this vdm; other programs running in different vdm will continue to run normally. Similarly, the 16-bit Windows applications running in different vdm have different input queues, which means that if a program temporarily loses response, applications in independent vdm can continue to obtain input.
Value: create_shared_wow_vdm
Meaning: (only applicable to Windows NT) this flag is valid only when a 16-bit windows application is running. If the defaultseparatevdm option of windows in win. ini is set to true, this identifier causes the CreateProcess function to bypass this option and run a new process on the shared virtual DOS host.
Value: create_suincluded
Meaning: the main thread of the new process will be created in the paused State and will not run until the resumethread function is called.
Value: create_unicode_environment
Description: If this parameter is set, the Environment block specified by the lpenvironment parameter uses Unicode characters. If it is null, the Environment block uses ANSI characters.
Value: debug_process
Meaning: If this flag is set, the calling process will be treated as a debugging program, and the new process will be treated as a debugged process. The system notifies the debugger of all debugging events of the program to be debugged.
If you use this flag to create a process, only the process that calls the CreateProcess function can call the waitfordebugevent function.
Value: debug_only_this_process
Meaning: If this flag is not set and the calling process is being debugged, the new process will become another debugging object of the debugger for debugging the calling process. If the calling process is not debugged, the related debugging behaviors will not be generated.
Value: detached_process
Meaning: For console processes, the new process has no permission to access the console of the parent process. You can use the allocconsole function to create a new console. This flag cannot be used with the create_new_console flag.
The dwcreationflags parameter is also used to control the priority of a new process. The priority class is used to determine the priority of the thread scheduling of the process. If none of the following priority class labels are specified, the default priority class is normal_priority_class unless the created process is idle_priority_class. In this case, the default priority class of the sub-process is idle_priority_class.
It can be one of the following signs:
Priority: high_priority_class
Meaning: indicates that the process will execute a time critical task, so it must be run immediately to ensure correctness. Programs with this priority take precedence over programs with normal or idle priority. One example is the Windows Task List. To ensure immediate response when a user calls the task, the system load is not considered. Be sure to exercise caution when using a high-priority CPU because a high-priority CPU-associated application can take up almost all of the CPU availability time.
Priority: idle_priority_class
Meaning: indicates that the thread of the process runs only when the system is idle and can be interrupted by any high-priority task. For example, screen saver. The idle priority is inherited by the quilt process.
Priority: normal_priority_class
Meaning: indicates that this process has no special task scheduling requirements.
Priority: realtime_priority_class
Meaning: indicates that the process has the highest priority available. A thread with a real-time priority can interrupt the execution of all other process threads, including the system processes that are executing important tasks. For example, a real-time process with a longer execution time may cause insufficient disk cache or slow mouse response.
Lpenvironment: point to the Environment block of a new process. If this parameter is null, the new process uses the environment of the called process.
An environment block exists in a block consisting of a string ending with null. This block also ends with null. Each string is in the form of name = value.
Because the equal sign is used as a separator, it cannot be used as a variable name by environment variables.
Instead of using the environment block provided by the application, it is better to set this parameter to null directly, and the current directory information on the system drive will not be automatically passed to the newly created process. For more information about this situation and how to handle it, see the Notes section.
The environment block can contain Unicode or ANSI characters. If the environment block to which lpenvironment points contains Unicode characters, the create_unicode_environment flag of the dwcreationflags field will be set. If the block contains ANSI characters, the flag is cleared.
Note that an ANSI environment block ends with two zero Bytes: one is the end of the string, and the other is used to end the fast. One Unicode environment block ends with four zero bytes of oil: Two represents the end of the string, and the other two are used to end the block.
Lpcurrentdirectory: point to a null-ending string used to indicate the working path of the child process. This string must be an absolute path containing the drive name. If this parameter is blank, the new process uses the same drive and directory as the called process. This option is the primary condition for a shell that needs to start the application and specify their drives and working directories.
Lpstartupinfo: point to the startupinfo struct used to determine how the new process's main form is displayed.
Lpprocessinformation: point to a process_information structure used to receive the recognition information of new processes.
Return Value:
If the function is successfully executed, a non-zero value is returned.
If the function fails to be executed and zero is returned, you can use the getlasterror function to obtain additional error information.
Note:
The CreateProcess function is used to run a new program. The winexec and loadmodule functions are still available, but they are also implemented by calling the CreateProcess function.
In addition, the CreateProcess function creates a process and a thread object. This thread will be created together with an initialized stack. The size of the stack is determined by the description in the executable file header. The thread starts execution at the file header.
The handles of new processes and new threads are created with global access permissions. If there is no security descriptor for either of the two handles, the handle can be used in any function that requires the handle type as a parameter. When the security descriptor is provided, when the handle is used in the next step, the access permission check is always performed first. If the access permission check denies access, the requested process cannot use this handle to access this process.
This process is assigned a 32-bit process identifier. The identifier is valid until the process is aborted. It can be used to identify the process or be specified in the OpenProcess function to open the handle of the process. A 32-bit thread identifier will be allocated to the initialized thread in the process. This identifier is valid until the county seat is terminated and can be used to uniquely identify this thread in the system. These identifiers are returned in the process_information struct.
When you specify an application name in the lpapplicationname or lpcommandline parameter, whether or not the application name contains an extension name does not affect the operation. The exception is. the MS-DOS program or Windows program with COM Extension must contain. COM Extension.
You can call the waitforinputidle function to wait for the new process to complete its initialization and wait for user input. This is extremely useful for synchronization between the parent process and the child process, because the CreateProcess function does not wait for the new process to complete its initialization. For example, before attempting to associate a window with a new process, the process should call waitforinputidle.
The preferred way to end a process is to call the exitprocess function, because this function notifies all the dynamic link library (DLLs) programs of the process to end. Other methods to terminate the process do not notify the associated dynamic link library. Note that when a process calls exitprocess, other counties of the process do not have the opportunity to run any other code (including the termination code associated with the dynamic link library ).
Exitprocess, exitthread, createthread, and createremotethread are serialized in the process when a process is started (the CreateProcess result is called. In an address space, only one of these events can occur at a time. This means that the following restrictions will be retained:
* New Threads can be created during the start and DLL initialization phases, but they cannot start running until the process's dll Initialization is complete.
* There can be only one thread in the Process of DLL initialization or removal.
* The exitprocess function does not return until all threads initialize or unload the DLL.
Before all threads in a process terminate and all handles of the process and their threads are terminated by calling the closehandle function, the process will remain in the system. Both process and main thread handles must be closed by calling the closehandle function. If you no longer need these handles, you 'd better close them immediately after creating the process.
When the last thread in the process is terminated, the following events occur:
* All objects opened by the process are closed.
* The termination status of a process (returned by the getexitcodeprocess function) changes from its initial value still_active to the end status of the last terminated thread.
* The thread object of the main thread is set to the flag State for other threads waiting for this object to use.
* The process object is set to the flag State for use by other threads waiting for this object.
Assume that the current directory on disk C is/msvc/MFC and there is an environment variable called C:. Its value is C:/msvc/mfc, as previously mentioned in lpenvironment, directory information on such a system drive is not automatically transmitted to the new process when the lpenvironment parameter of the CreateProcess function is not empty. An application must manually pass the current directory information to the new process. To do this, the application must directly create environment strings and arrange them alphabetically (because Windows NT and Windows 95 use a simple environment variable ), and put them into the environment block specified in lpenvironment. Similarly, they need to find the beginning of the Environment block and repeat the sorting of the Environment block mentioned above.
One way to get the current directory variable of drive X is to call getfullpathname ("X :",..). This avoids the need for an application to scan the environment block. If the absolute path returned is X:/, you do not need to pass this value as an environment data because the root directory is the default current directory of the new process on drive X.
The handle returned by the CreateProcess function has the process_all_access permission on the process object.
The current directory of the sub-process object in the current directory specified by the lpcurrentdirectory parameter. The second project specified by the lpcommandline parameter is the current directory of the parent process.
For Windows NT, when a process is created with create_new_process_group specified, a call to setconsolectrlhandler (null, true) is used in the new process, this means that Ctrl + C is invalid for the new process. This allows upper-level surgical programs to process Ctrl + C information themselves and selectively transmit these signals to sub-processes. CTRL + break is still valid and can be used to interrupt the execution of the Process/process tree.
Security note:
The first parameter lpapplicationname may be null. In this case, the name of the executable file must be in lpcommandline, And the lpcommandline parameter can contain spaces. If the executable file or path contains spaces, the execution of the file may be incorrect. This is caused by the Space Parsing Method of this function. For example, the following example is dangerous. If the project runs program.exefile in a diagram, the example runs on behalf of the myapp.exe file.
CreateProcess (null, "C: // program files // myapp.exe ",.......)
If a malicious user writes a file named program.exe in the system, any program that calls the CreateProcess function and uses the program filesfolder in the file path can run the program.exe file instead of the file to be run.
To avoid this problem, do not pass the null value to the lpapplicationname parameter, or use double quotation marks (escape characters) in lpcommandline to enclose the full path name of the executable file, as shown below:
CreateProcess (null, "/" C: // program files // myapp.exe/"-l-S ",.......)
-Land -sare parameters of the myapp.exe executable file.
The last note is that the parameters in lpapplicationname are the same as the first parameter in lpcommandline. Some people say that they are somewhat repetitive. In fact, this is simply a habit of being recognized!
See
Allocconsole, closehandle, handler, createthread, exitprocess, exitthread, response, getcommandline, response, getexitcodeprocess, response, getstartupinfo, getsystemdirectory, getwindowsdirectory, loadmodule, OpenProcess, process_information, response, seterrormode, startupinfo, terminateprocess, waitforinputidle, waitfordebugevent, winexec
Quick info:
Import to database: kernel32.lib
Header file: WINBASE. h
Simple Example:
# Include <iostream>
# Include <windows. h>
Using namespace STD;
Int main ()
{
Tchar szcmdline [] = {text ("D: // test // te.exe")}; // added by Jianghu Sanjiao
Startupinfo Si; // some required parameter settings
Memset (& Si, 0, sizeof (startupinfo ));
Si. cb = sizeof (startupinfo );
Si. dwflags = startf_useshowwindow;
Si. wshowwindow = sw_show;
Process_information PI; // The required parameter is set to complete.
// Lpcommandline cannot be written as a constant of "D: // test // te.exe" and changed to tchar szcmdline [] = {"D: // test // te.exe "}
// Change lpcommandline to tchar szcmdline [] = {text ("D: // test // te.exe ")};
If (! CreateProcess (null, szcmdline/* "D: // test // te.exe" */, null, null, false, 0, null, null, & Si, & PI ))
// If (! CreateProcess (null, "d: // test // te.exe", null, null, false, 0, null, null, & Si, & PI) // "D: // test // te.exe "is the path of the program you want to run //
{
Cout <"create fail! "<Endl;
Exit (1 );
}
Else
{
Cout <"sucess! "<Endl;
}
Return 0;
}

 
 

Differences:
Function: CreateProcess> ShellExecute> winexec is also complex!

Winexec () is only used for executable files. It is an old function. It is easy to use but not recommended! (Poor compatibility)
Shellexcute () is to open any file through the Windows Shell, non-executable files automatically open through the associated program for executable files, the difference is not big, but shellexcute can specify the working path at runtime

Winexec () must have getmessage or timeout before returning! Both CreateProcess and ShellExecute are directly returned!

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/duck04551/archive/2009/07/01/4312260.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.