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. For example, winexec('notepad.exe readme.txt ', sw_show );
ShellExecute can run not only EXE files, but also associated files.
First, you must reference the shellapi. Pas unit: Uses shellapi;
1. Standard usage
The meanings of the parameters and prototype of the ShellExecute Function are as follows:
Function ShellExecute (hwnd: hwnd; operation, filename, parameters, directory: pchar; showcmd: integer): hinst; stdcall;
● 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.
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 ', nil, nil, sw_shownormal );
Format 2: http: // website domain name/Webpage file name.
Example: ShellExecute (handle, 'open', 'HTTP: // www.neu.edu.cn/default.htm', 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: ', nil, nil, 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 ', nil, nil, sw_shownormal); open the new mail window and automatically fill in the recipient address. If multiple recipient addresses are specified, the recipient addresses must be separated by semicolons or commas (,), for example, ShellExecute (this-> m_hwnd, "open ",
"Mailto: nishinapp@yahoo.com", "", "", sw_show); this can activate Outlook Express.
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 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.
Go to ShellExecute
Translator: Xu Jingzhou (Original: nishant S)
Q: How to open an application? ShellExecute (this-> m_hwnd, "open", "calc.exe", "", "", sw_show );
Or ShellExecute (this-> m_hwnd, "open", "notepad.exe ",
"C: // mylog. log", "", sw_show );
As you can see, I have not passed the complete path of the program.
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.google.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; // This is an [in] Parameter
Zeromemory (& startupinfo, sizeof (startupinfo ));
Startupinfo. cb = sizeof startupinfo; // only compulsory field
If (CreateProcess ("C: // winnt // notepad.exe", null,
Null, 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 );
How can I use the CreateProcess function correctly?
Function prototype
BOOL CreateProcess(
LPCTSTR lpApplicationName, // name of executable module
LPTSTR lpCommandLine, // command line string
LPSECURITY_ATTRIBUTES lpProcessAttributes, // SD
LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
BOOL bInheritHandles, // handle inheritance option
DWORD dwCreationFlags, // creation flags
LPVOID lpEnvironment, // new environment block
LPCTSTR lpCurrentDirectory, // current directory name
LPSTARTUPINFO lpStartupInfo, // startup information
LPPROCESS_INFORMATION lpProcessInformation // process information
);
(1) lpctstr lpapplicationname
The name of the executable file to be run (should contain the extension ). If the file cannot be found, CreateProcess fails to run. It should be set to null.
(2) lptstr lpcommandline
The command line string passed to the new process, which should be the address of a very large number of strings. You can set a specific command line. If the first tag does not have an extended name, createprocessset it to .exe. If the file cannot be found, CreateProcess searches and runs according to the Environment setting directory.
(3) lpsecurity_attributes
Sets the security of process objects. Null can be passed for these parameters. In this case, the system assigns default security descriptors to these objects. (Not clear)
(4) lpsecurity_attributes lpthreadattributes
Sets the thread object security. Null can be passed for these parameters. In this case, the system assigns default security descriptors to these objects. (Not clear)
(5) bool binherithandles
The parent process is set to false.
(6) DWORD dwcreationflags
Used to identify a flag to specify how to create a new process.
Description
The ebug_process parent process wants to debug any processes generated by the child process and child process in the future. When some events occur in any sub-process (the debugged process), the parent process is notified. (Not clear)
The debug_only_this_process flag is similar to the debug_process flag. The debug program is only notified of specific events in the child process that is closely related to the parent process. (Not clear)
Create_suincluded the new process is created, but its main thread is suspended.
Detached_process blocks access by a Cui-based process to the console window of its parent process and tells the system to send its output to the new console window.
Create_new_console creates a new console window for the new process. If both the create_new_console and detached_process flag are set, an error is returned.
Create_no_window does not create any console window for the application.
Create_new_process_group modifies the list of processes notified when you press Ctrl + C or Ctrl + break.
Create_default_error_mode does not inherit the error mode used by the parent process.
Create_separate_wow_vdm can only be used when you run a 16-bit Windows Application on Windows2000. Tells the system to create a single DoS Virtual Machine (vdm) and run a 16-bit windows application in the vdm. (Not clear)
Create_shared_wow_vdm can only be used when you run a 16-bit Windows Application on Windows2000. Run a 16-bit windows application in the system's shared vdm. (Not clear)
Create_unicode_environment tells the system that the Environment block of a sub-process should contain Unicode characters. According to the default settings, the process environment block contains an ANSI string.
Create_forcedos forces the system to run a MOS-DOS application embedded with a 16-bit OS/2 application.
Create_breakaway_from_job enables the process in the job to generate a new process associated with the job (not clear ).
Worker idle less than normal (Windows2000) normal higher than normal (Windows2000) high real-time
For most applications, priority classes should not be set.
(7) lpvoid lpenvironment
Point to the memory block that contains the environment string to be used by the new process. In most cases, null is passed for this parameter so that the child process can inherit a group of Environment strings that the parent process is using. You can also use the getenvironmentstrings function to call the freeenvironmentstrings function to release memory blocks when this memory block is no longer needed.
(8) maid directory
Set the current drive and directory of the sub-process. If this parameter is null, the working directory of the new process is the same as the directory of the application that generates the new process. If this parameter is not null, it must point to a string that ends with 0 containing the required drive and working directory. Note: You must set the drive name in the path.
(9) lpstartupinfo
Initialization is required first.
Member window/console Function
Both CB and CB are used for version control. Must be initialized to sizeof (startupinfo)
Both lpreserved and lpreserved are retained. Must be initialized to null (not null)
Both lpdesktop and lpdesktop identify the name of the desktop where the application is started. If the desktop does not exist, create a desktop with the default attribute and use the name specified for the new process. When its value is null, it is associated with the current desktop. (Not clear)
Set the name of the console window in the lptitle console. If the value is null, the name of the executable file is used as the window name.
Dwxdwy both sets the position of the application window on the screen (in pixels ). These two coordinates are used only when the child process uses cw_usedefault as the X parameter of createwindow to create its first overlapped window.
Dwxsizedwysize both sets the width and length of the application window (in pixels). Only when the sub-process uses cw_usedefault as the nwidth parameter of createwindow to create its first overlapping window, to use these values.
Dwxcountcharsdwycountchars console sets the width and height of the console window of the sub-application (in characters)
Set the text and background color of the console window on the dwfillattribute Console
Both dwflags are described in the following table.
The wshowwindow specifies how the first overlapping window of the application appears if the showwindow called by the Child application for the first time passes sw_showdefault as the ncmdshow parameter.
Both cbreserved2 are retained. Must be initialized to 0 (not 0)
Both lpreserved2 are retained. Must be initialized to null (why)
The hstdinputhstdoutputhstderror console sets the handle of the console input/output cache. The keyboard cache and hstdoutput and hstderror are identified by the mohstdinput.
Dwflags usage:
Logo meaning
Startf_usesize use dwxsize and dwysize members
Startf_useshowwindow use wshowwindow members
Startf_useposition use dwx and dwy members
Startf_usecountchars uses the dwxcountchars and dwycountchars members
Startf_usefillattribute use a dwfillattribute Member
Startf_usestdhandles use hstdinput, hstdoutput, and hstderror members
Startf_run_fullscreen forces console applications running on x86 computers to run in full screen mode
When startf_forceonfeedback starts a process, the system arrow cursor is changed to an hourglass arrow cursor temporarily.
When startf_forceofffeedback starts a process, the cursor is not changed to an hourglass.
(10) lpprocess_information lpprocessinformation
The returned information of the new process. Hprocess is the handle of the new process kernel object; hthread is the handle of the new thread kernel object. After use, closehandle should be released to reduce the usage count of the kernel by one. Dwprocessid: ID of the new process; dwthreadid: ID of the new thread. 0 cannot be the ID. Although the system does not have the same ID number at the same time, when the Kernel Handle of a process is released, its ID number may be used by new processes. To ensure that the process ID or thread ID is not reused, the only method is to ensure that the kernel object of the process or thread is not revoked. If a new process or thread has just been created, as long as the handle of these objects is not closed, the process object will not be undone. Once the application stops using this ID, you can call closehandle to release the kernel object. Remember that using or relying on the process ID is no longer secure. If a child process is used, the validity of the parent process or parent thread cannot be guaranteed, unless the parent process copies its own process object or thread object handle, and let the sub-process inherit these handles.
# Include "windows. H"
# Include "stdio. H"
Int main ()
{
-
If (readfile (houtputread, buffer, 4095, & bytesread, null) = NULL)
{
Break;
}
Printf (buffer); // output
Sleep (500 );
Security_attributes SA, SA2;
Handle hinputread, hinputwrite;
Handle houtputread, houtputwrite;
// Createpipe1
SA. nlength = sizeof (security_attributes );
SA. lpsecuritydescriptor = NULL;
SA. binherithandle = true;
If (! Createpipe (& houtputread, & houtputwrite, & SA, 0 ))
{
Printf ("error on createpipe1 success 〃);
Return 0;
}
// Createpipe2
Sa2.nlength = sizeof (security_attributes );
Sa2.lpsecuritydescriptor = NULL;
Sa2.binherithandle = true;
If (! Createpipe (& hinputread, & hinputwrite, & SA2, 0 ))
{
Printf ("error on createpipe2 failed 〃);
Return 0;
}
// CreateProcess
Startupinfo Si;
Process_information PI;
Si. cb = sizeof (startupinfo );
Getstartupinfo (& Si );
Si. hstderror = houtputwrite;
Si. hstdoutput = houtputwrite;
Si. hstdinput = hinputread;
Si. wshowwindow = sw_hide;
Si. dwflags = startf_useshowwindow | startf_usestdhandles;
DWORD dwwritten;
If (! CreateProcess (null, (program name), null, null, true, null, & Si, & PI ))
{
Printf ("error on CreateProcess ");
Return 0;
}
Closehandle (hinputread );
Closehandle (houtputwrite );
// Write and read
Char szinput [20] =... ; // Set the input content
Writefile (hinputwrite, szinput, strlen (szinput), & dwwritten, null );
Char buffer [4096] = {0 };
DWORD bytesread;
While (true)
{
}
Closehandle (hinputwrite );
Closehandle (houtputread );
System ("pause ");
}
# Include "windows. H"
# Include "stdio. H"
Int main ()
{
-
If (readfile (houtputread, buffer, 4095, & bytesread, null) = NULL)
{
Break;
}
Printf (buffer); // output
Sleep (500 );
Security_attributes SA, SA2;
Handle hinputread, hinputwrite;
Handle houtputread, houtputwrite;
// Createpipe1
SA. nlength = sizeof (security_attributes );
SA. lpsecuritydescriptor = NULL;
SA. binherithandle = true;
If (! Createpipe (& houtputread, & houtputwrite, & SA, 0 ))
{
Printf ("error on createpipe1 success 〃);
Return 0;
}
// Createpipe2
Sa2.nlength = sizeof (security_attributes );
Sa2.lpsecuritydescriptor = NULL;
Sa2.binherithandle = true;
If (! Createpipe (& hinputread, & hinputwrite, & SA2, 0 ))
{
Printf ("error on createpipe2 failed 〃);
Return 0;
}
// CreateProcess
Startupinfo Si;
Process_information PI;
Si. cb = sizeof (startupinfo );
Getstartupinfo (& Si );
Si. hstderror = houtputwrite;
Si. hstdoutput = houtputwrite;
Si. hstdinput = hinputread;
Si. wshowwindow = sw_hide;
Si. dwflags = startf_useshowwindow | startf_usestdhandles;
DWORD dwwritten;
If (! CreateProcess (null, (program name), null, null, true, null, & Si, & PI ))
{
Printf ("error on CreateProcess ");
Return 0;
}
Closehandle (hinputread );
Closehandle (houtputwrite );
// Write and read
Char szinput [20] =... ; // Set the input content
Writefile (hinputwrite, szinput, strlen (szinput), & dwwritten, null );
Char buffer [4096] = {0 };
DWORD bytesread;
While (true)
{
}
Closehandle (hinputwrite );
Closehandle (houtputread );
System ("pause ");
}