C # call external exe (2021.4.15)

C # call external exe

In the development process of C#Windows form application, for example, to make a large system and integrate the functions of many other applications, we can use the existing executable exe program to enrich and improve the system.

1. Call external exe (no parameters passed in)

QQ.exe

1.1 call QQ by CMD Exe (no parameters passed in)

First, Enter the C:\Program Files (x86)\Tencent\QQ\Bin folder, hold down the Shift key in the blank space on the right and click the right mouse button. Select here to open the command line window and Enter QQ with the keyboard Exe press Enter to run QQ program, as shown in the figure below.


1.2 C# simulate cmd to call external exe (no incoming parameters)

Open Visual Studio 2015 and create a new c# - > Windows Forms application. Enter the project name into InvokeQQ and confirm. After entering the project, a Form1 form will be automatically generated.


Click the toolbox on the left side of the Form1 form, drag the Button into the Form1 form, then right-click the Button and select properties, modify the Text name of the Button to start external QQ, and double-click the Button to enter the click trigger event function Button1 of the Button_ Click, enter three lines of code in the function to call the external QQ Exe program, and the corresponding library is introduced at the same time,

using System.Diagnostics;//Put it with other using
Process m_Process = new Process();
m_Process.StartInfo.FileName = "C:\\Program Files (x86)\\Tencent\\QQ\\Bin\\QQ.exe";//QQ. Full path of the folder where exe is located
m_Process.Start();



Then click the start button above to run the project. After the project runs, the Form1 form will be opened. Click the button in the form with the mouse to pop up the QQ application. The running results are shown in the figure below.

2. Call external exe (parameters need to be passed in)

2.1 create a new C + + project and generate an exe program that needs to pass in parameters


Open Visual Studio 2015, create a new Visual C + ± > win 32 console application, enter the project name as WithParameterApp and click OK. In the pop-up window, select an additional option to select an empty project. After generating the project, right-click add - > new item on the source file under WithParameterApp under the solution on the right, select C + + file and enter the name as main cpp. Copy the following code to main After running in CPP, the parameter WithParameterApp to be passed in can be generated in the corresponding folder Exe program, which is used to calculate the sum of two numbers. After running in VS, the result is shown in the figure below (1 parameter by default).

#include <iostream>
using namespace std;
/*** Convert string to int***/
int char2int(const char* str) {
	const char* p = str;
	bool neg = false;
	int res = 0;
	if (*str == '-' || *str == '+') {
		str++;
	}

	while (*str != 0) {
		if (*str < '0' || *str > '9') {
			break;
		}
		res = res * 10 + *str - '0';
		str++;
	}

	if (*p == '-') {
		res = -res;
	}
	return res;
}
void main(int argc, char *argv[])
{
	int cc=0;
	std::cout << "Total input" << argc << "Parameters" << endl;
	for(int i=0;i<argc;i++)
		std::cout << argv[i] << endl;
	if(argc ==3)
		std::cout << "The sum of the two numbers is" << char2int(argv[1]) + char2int(argv[2]) << endl;
	system("pause");
}



As shown in the above figure, withparameterapp has been generated in D:\Visual Studio 2015\MyProjects\WithParameterApp\Debug folder exe.

2.1.1 cmd calls external exe (pass in parameters)

Open the cmd window under D:\Visual Studio 2015\MyProjects\WithParameterApp\Debug folder, enter the following command and press enter: withparameterapp exe 456 789

It can be seen that the sum of 456 and 789 is 1245

2.1.2 C# simulate cmd to call external exe (pass in parameters)

In the C# Windows form application named InvokeQQ above, add another Button in the Form1 form, change the Text property of the Button to InvokeWithParameterApp, double-Click the Button, enter the following code in the Click event function of the Button to call the external exe (pass in parameters), and then Click the green Button to run above, The results are shown in the figure below.

Process cmd = new Process(); 
cmd.StartInfo.FileName = @"D:\Visual Studio 2015\MyProjects\WithParameterApp\Debug\WithParameterApp.exe";
cmd.StartInfo.WorkingDirectory = @"D:\Visual Studio 2015\MyProjects\WithParameterApp\Debug\"; 
cmd.StartInfo.CreateNoWindow = false;//Show command line window
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
string param1 = "456", param2 = "789";
cmd.StartInfo.Arguments = param1+" "+param2;
cmd.Start();

2.2 call external exe (pass in parameters with different paths)

2.2.1 cmd calls external Python script py (pass in parameters with different paths)

python.exe

algorithm123. The comments in the PY script file should not be in Chinese, which can effectively avoid encoding and decoding errors

#-*- coding:utf-8 -*-
import sys
from os.path import exists

print(sys.argv[1])
print(sys.argv[2])
from_name = sys.argv[1]
to_name = sys.argv[2]

source=open(from_name)
indate=source.read()
print(indate)
source.close()

target=open(to_name,'w')
target.write(indate)
target.close()



Win+R opens the operation window, enter cmd to open the command line window, and then enter the following command to realize the use of D: \ anaconda3 \ python Exe to execute e: \ algorithm123 \ algorithm123 Py script, and then E: \ exception \ exception Copy to file 123456: \ exhmergorite.txt txt.

D:\Anaconda3\python.exe E:\algorithm123\algorithm123.py E:\abnormal\abnormal.txt E:\algorithm123ExeResult\123456.txt

2.2.2 C# simulate cmd to call external Python script py (pass in parameters with different paths)

In the C# Windows form application named InvokeQQ in the above project, add a Button again in the Form1 form, change the Text property of the Button to Invokealgorithm123, double-Click the Button, enter the following code in the Click event function of the Button to call the external exe (pass in the parameters with different paths), and then Click the run green Button above, The results are shown in the figure below.

Process cmd = new Process(); 
cmd.StartInfo.FileName = @"D:\Anaconda3\python.exe";//If necessary, set the python environment to the front of the environment variable Path
cmd.StartInfo.UseShellExecute = false; //This must be false, otherwise an exception will be thrown
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.WorkingDirectory = "E:\\algorithm123\\";
cmd.StartInfo.CreateNoWindow = true;//Do not display the command line window
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
string path1 = "E:\\algorithm123\\algorithm123.py",path2= "E:\\abnormal\\abnormal.txt", path3= "E:\\algorithm123ExeResult\\12345678.txt";
cmd.StartInfo.Arguments = path1+" "+path2+" "+path3;
cmd.Start(); //Start process
MessageBox.Show("File copied successfully!");


2.3 C# simulate cmd to call external Python packaged exe (pass in parameters with different paths)

2.3.1 use pyinstaller to package py script files into executable exe (pass in parameters with different paths)

First, you can create a new virtual environment with conda create -- name mypython python python = 3.6. After configuring the Tsinghua image, you can download and install the dependent package. conda activate mypython enters the virtual environment, and then pip list to view the installed package. Because the PY script file can package the existing py file as an exe executable through pyinstaller. Therefore, two packages pip install pyinstaller and pip insatl requests should be installed. The list of installed packages is shown in the figure below.


Let's use Pyinstaller to py is packaged into exe. For the convenience of packaging, I set python in the virtual environment to the system environment variable Path, that is, put D:\Anaconda3\envs\mypython and D:\Anaconda3\envs\mypython\Scripts at the top of the Path variable value. After confirmation, test whether python and pip are installed and configured successfully in cmd, as shown in the following figure.


Then at algorithm123 After opening cmd in the E:\algorithm123 folder where the PY script file is located, enter the following command: pyinstaller - F algorithm23 Py, after running, you will be prompted that the package is successfully packaged into exe, and there are more in the folder - pycache_ build and dist folders and algorithm123 Spec file, including the packaged algorithm123 in dist exe.


2.3.2 cmd calls exe packaged by external py script (pass in parameters with path)

Now open the dist folder and open the cmd command line window under this folder to test the packaged algorithm123 If exe can run successfully, enter the following command: algorithm123 Exe e: \ exception \ exception txt E:\algorithm123ExeResult\123456789exe.txt, the cmd window displays the correct execution result, and 123456789exe.exe is successfully generated in the E: \ algorithm123exeresult folder Txt file, as shown in the figure below.

2.3.3 C# simulate cmd to call exe packaged by external py script (pass in parameters with path)

In the C# Windows form application named InvokeQQ in the above project, add a Button again in the Form1 form, and change the Text property of the Button to invokealgorithm123 Exe, double-Click the Button, enter the following code in the Click event function of the Button to call the external py script packaging exe (pass in the parameters with different paths), and then Click the run green Button above. The run result is shown in the figure below.

Process cmd = new Process();
cmd.StartInfo.FileName = @"E:\algorithm123\dist\algorithm123.exe";
cmd.StartInfo.UseShellExecute = false; //This must be false, otherwise an exception will be thrown
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.WorkingDirectory = "E:\\algorithm123\\dist\\";
cmd.StartInfo.CreateNoWindow = true;//Do not display the command line window
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
string path1 = "E:\\abnormal\\abnormal.txt", path2 = "E:\\algorithm123ExeResult\\123456exe.txt";
cmd.StartInfo.Arguments = path1 + " " + path2;
cmd.Start();
MessageBox.Show("Call external Python Script packaging exe Execute file copy succeeded!");


Keywords: Python C# pip conda exe

Added by Dustin013 on Mon, 07 Mar 2022 17:07:13 +0200