Reference C/C ++ to run external programs or open files

Source: Internet
Author: User

Other considerations for the three SDK functions: winexec, ShellExecute, and CreateProcess:

[1] define the header file
The following two header files must be defined:

# Include <shlobj. h> // you can replace it with windows. h.
# Include <shellapi. h>

If the header file # include <windows. h> is defined, # include <shlobj. h> is not required.

[2] define a path
The path in C ++ must be "\" rather than "\", so the preceding three functions indicate the path as Disk: \ directory \\... \ file name

Winexec ("d :\\ Program Files \ test \ test.exe", sw_showmaximized );
ShellExecute (null, "open", "C: \ test.txt", null, null, sw_shownormal );

1. Call the API: INT system (const char * command );

You can run a command to start a program. For example, "Ping www.vccode.com", "yourexe", etc.

However, there are several points worth noting:

(1) he will not return immediately until the execution of the program you started is completed.

(2) If you start a Windows program, it will still start a console, which makes people feel bad, but if it is a console, and you need to wait for it to complete, it will be a good choice.

(3) Its return value indicates whether execution is successful and the exit code of the program.
(4) The *. txt file or "www.baidu.com" cannot be run"


2. Call the API:

Uint winexec (

Maid, // command line

Uint ucmdshow // window style

);

This API is as easy to use as the API: system, and uses the command line type.

However, it has several advantages over API: System:

(1) it starts a new process and returns immediately, so your program does not have to wait.

(2) It has another parameter: ucmdshow, through which you can control the display of the form to a certain extent, such as letting it run in the background without displaying it.

(3) It does what you want to do no matter whether you start the console program or the windows program.


Its shortcomings:

(1) It is completely out of the process and cannot be controlled as necessary

(2) You cannot know whether the started program is exited.

(3) the exit code of the started program is not obtained.
(4) The *. txt file or "www.baidu.com" cannot be run"

3. call:

Hinstance ShellExecute (

Hwnd,

Lpctstr lpverb,

Lpctstr lpfile,

Lptstr lpparameters,

Lpctstr lpdirectory,

Int nshowcmd

);

It also has the same disadvantage as winexec.

Although it returns an hinstance, it is not a real handle. We can only use it for some error value checks.

However, it is more powerful than the first two. It executes the shell commands of the system.

If "xx.txt" is uploaded to 12.162, it cannot be executed successfully, but ShellExecute can be executed well. It starts a default text processing program to open it.

If "www.vccode.com" is input in 1 and 2, it cannot be executed successfully, but ShellExecute can be executed well. It will start a default browser to open this website.


Parameter description:

Parameter 1 hwnd: A form handle, which serves as the parent form of the Startup Program.

Parameter 2 lpverb: the operation you want to perform (edit, release E, find, open, print, properties), you can also input a null value, it will perform the default operation (Win2000 is slightly different from later processing, see msdn ).

Parameter 3 lpfile: an object with a file name or operation.

Parameter 4 lpparameters: If lpfile is an executable file, this parameter is used as its parameter. Its format is determined by the executed operation. When lpfile is a document file, this parameter must be null.

Parameter 5 lpdirectory: Specify its working directory.

Parameter 6 nshowcmd: controls the display of the form.


The following are examples:

// Start a doscommand and start Windows programs with the same

: ShellExecute (this-> getsafehwnd (), null, "ping", "www.vccode.com", null, sw_shownormal );


// Open a file

: ShellExecute (this-> getsafehwnd (), "open", "readme.txt", null, null, sw_shownormal );

// The above verb can be passed or not, but if "readme.txt" is "readme. Bat", you must specify it. Otherwise, it will be executed as a command rather than opened.


// Open a directory

: ShellExecute (this-> getsafehwnd (), "open", "C:", null, null, sw_shownormal );


// Open the webpage

: ShellExecute (this-> getsafehwnd (), "open", "www.vccode.com", null, null, sw_shownormal );



// Browse a directory

ShellExecute (handle, "Explore", "C:" null, null, sw_shownormal );


// View the attributes of a file or directory

// Use shellexecuteex. For the implementation, see the corresponding part of the source code.


If there is no special control requirement, it can do a lot for us, but when we must be able to control the startup process, we have to use 4th points.



4. Call the API:

Bool CreateProcess (

Lptstr 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

Maid directory, // current directory name

Lpstartupinfo, // startup information

Lpprocess_information lpprocessinformation // Process Information

);

It is often daunting to see this function. It has many parameters, and the parameter types are also quite different. Yes, it is because of this that it is powerful!

But do not be afraid. It is generally used and very simple! The following is a simple example (start notepad ):


Startupinfo startinfo;

Process_information pinfo;

// Do not set the startup information of the program. All settings are cleared.

Memset (& startinfo, 0, sizeof (startupinfo ));

Startinfo. cb = sizeof (startupinfo); // you can specify the structure size.


Bool ret = CreateProcess (

Null, // Startup Program path name

"Notepad.exe", // parameter (when the exename is null, you can put the command before the parameter)

Null, // use the default process Security Attribute

Null, // use the default thread Security Attribute

False, // handle does not inherit

Normal_priority_class, // use normal priority

Null, // use the environment variable of the parent process

Null, // specify the working directory

& Startinfo, // how to display the subprocess Main Window

& Pinfo); // used to store the returned information of the new process


After the creation is successful, we can find the process handle, thread handle, process ID, and thread ID from pinfo.

The source code of the attachment demonstrates that the program is started and stopped.


In fact, we can achieve more control through many methods, such as memory sharing, parent process form sentence body passing in, and obtaining the sub-process form handle from the message.


For more information about CreateProcess, see <Windows System Programming> published by the People's post and telecommunications Publishing House. Its "process" section is described in detail.

Routine:

# Include <windows. h>

# Include <shellapi. h>

# Include <stdio. h>

Void main ()

{

Hwnd handle;

Printf ("function <winexec>: \ NIT can run a cmd command, but can't open *. txt and \" www. *. * \ "\ n ");

Printf ("Please press ENTER go on \ n ");

Getchar ();

Winexec ("mspaint.exe", sw_shownoactivate );

/* Winexec cannot open a website or TXT file */

Printf ("function <ShellExecute>: \ NIT can run a cmd command to open file or web \ n ");

Getchar ();

Printf ("open a TXT file \ n ");

ShellExecute (null, "open", "C: \ test.txt", null, null, sw_minimize );

Getchar ();

Printf ("open a WEB \ n ");

ShellExecute (null, null, "www.baidu.com", null, null, sw_showna );

Getchar ();

Printf ("Run a cmd command: Ping www.sina.com \ n ");

ShellExecute (null, null, "ping", "Sina.com", null, sw_shownormal );

Getchar ();

Printf ("open directory \ n ");

ShellExecute (null, "open", "C:", null, null, sw_shownormal );

Getchar ();

Printf ("Browse Directory \ n ");

ShellExecute (null, "Explore", "C:", null, null, sw_shownormal );

Getchar ();

Printf ("file attributes \ n ");

ShellExecute (handle, "properties", "C: \ test.txt", null, null, sw_minimize );

Printf ("% s", handle );

/* The second parameter of ShellExecute can be null for the operation you want to perform (edit, release E, find, open, print, properties */

}

/*

Sw_hide hides the window and passes activation to another window.

Sw_minimize minimizes the specified window and activates the top-level window in the system's list.

Sw_restore activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position (same as sw_shownormal ).

Sw_show activates a window and displays it in its current size and position.

Sw_showmaximized activates a window and displays it as a maximized window.

Sw_showminimized activates a window and displays it as an icon.

Sw_showminnoactive displays a window as an icon. The window that is currently active remains active.

Sw_showna displays a window in its current state. The window that is currently active remains active.

Sw_shownoactivate displays a window in its most recent size and position. The window that is currently active remains active.

Sw_shownormal activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position (same as sw_restore ).

*/

Related Article

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.