C# calls external exe (2021.4.15)

C# calls external exe

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

1. Call external exe (no incoming parameters)

insert image description here

QQ.exe

1.1 Call QQ.exe in cmd mode (no incoming parameters)

        First go to the C:\Program Files (x86)\Tencent\QQ\Bin folder, hold down Shiftthe key in the blank space on the right and click the right mouse button, choose to open the command line window here, and then use the keyboard to enterQQ.exePress the buttonEnter to run the QQ program, as shown in the figure below.

insert image description here
insert image description here

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

        Open Visual Studio 2015, create a new C#->Windows form application, enter the project name into InvokeQQ and confirm, and a Form1 form will be automatically generated after entering the project.
insert image description here
insert image description here
        Click on the toolbox on the left side of the Form1 form, drag the Button button into the Form1 form, then right-click on the Button and select Properties, modify the Text name of the Button button to start external QQ, and double-click the button to enter the click trigger event of the button Function button1_Click, enter three lines of code in the function to call the external QQ.exe program, and import the corresponding library at the same time,

using System.Diagnostics;//和其他的using放在一起
Process m_Process = new Process();
m_Process.StartInfo.FileName = "C:\\Program Files (x86)\\Tencent\\QQ\\Bin\\QQ.exe";//QQ.exe所在的文件夹全路径
m_Process.Start();

insert image description here
insert image description here
        Then click the start button above to run the project. After the project runs, the Form1 form will open. Click the button in the form with the mouse to pop up the QQ application. The running result is shown in the figure below.
insert image description here

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

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

insert image description here
        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 the empty project as an additional option, and after generating the project, under the WithParameterApp project under the solution on the right Right-click on the source file to add -> New item, select C++ file, and enter the name as main.cpp. Copy the following code into main.cpp and run it to generate the WithParameterApp.exe program in the corresponding folder. This program is used to calculate the sum of two numbers. The result after running in VS is shown in the figure below ( Defaults to 1 argument).

#include <iostream>
using namespace std;
/*** 将字符串转成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 << "总共输入" << argc << "个参数" << endl;
	for(int i=0;i<argc;i++)
		std::cout << argv[i] << endl;
	if(argc ==3)
		std::cout << "两个数的和为" << char2int(argv[1]) + char2int(argv[2]) << endl;
	system("pause");
}

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

2.1.1 cmd calls external exe (input parameters)

        Open the cmd window under the D:\Visual Studio 2015\MyProjects\WithParameterApp\Debug folder, enter the following command and press Enter: You WithParameterApp.exe 456 789
insert image description here
        can see that the sum of the two numbers 456 and 789 is 1245 in the running result.

2.1.2 C# simulates cmd to call external exe (incoming parameters)

        In the C# Windows form application whose project name is InvokeQQ, add another Button to the Form1 form, change the Text property of the Button to InvokeWithParameterApp, double-click the Button, and enter the following code in the Click event function of the Button to perform external Exe call (input parameters), and then click the run green button above, the result is 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;//显示命令行窗口
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
string param1 = "456", param2 = "789";
cmd.StartInfo.Arguments = param1+" "+param2;
cmd.Start();

insert image description here

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

2.2.1 cmd calls external Python script .py (input parameters with different paths)

python.exe
insert image description here

It is best not to include Chinese in the comments in the algorithm123.py py script file, 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()

insert image description here
insert image description here
        Win+ ROpen the running window, enter cmd to open the command line window, and then enter the following command to use D:\Anaconda3\python.exe to execute the E:\algorithm123\algorithm123.py script, and then copy the E:\abnormal\abnormal.txt file Copy to E:\algorithm123ExeResult\123456.txt .

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

insert image description here

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

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

Process cmd = new Process(); 
cmd.StartInfo.FileName = @"D:\Anaconda3\python.exe";//必要时可将python环境设置到环境变量Path的最前面
cmd.StartInfo.UseShellExecute = false; //此处必须为false否则引发异常
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.WorkingDirectory = "E:\\algorithm123\\";
cmd.StartInfo.CreateNoWindow = true;//不显示命令行窗口
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
string path1 = "E:\\algorithm123\\algorithm123.py",path2= "E:\\异常\\异常.txt", path3= "E:\\algorithm123ExeResult\\12345678.txt";
cmd.StartInfo.Arguments = path1+" "+path2+" "+path3;
cmd.Start(); //启动进程
MessageBox.Show("文件复制成功!");

insert image description here
insert image description here

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

2.3.1 Use pyinstaller to package the py script file into an executable exe (pass in parameters with different paths)

        First, you can use conda to create a virtual environment conda create --name mypython python=3.6. After configuring the Tsinghua mirror, you can download and install the dependency package, conda activate mypythonenter the virtual environment, and then pip listview the installed package. Because the py script file can use pyinstaller to package the existing py file into exe Executable program. So there are two packages to be installed pip install pyinstallerand pip insatll requeststhe list of installed packages is shown in the figure below.
insert image description here

insert image description here
        Next, use Pyinstaller to package .py into exe. For the convenience of packaging, I set the python in the virtual environment to the system environment variable Path, that is, D:\Anaconda3\envs\mypython and D:\Anaconda3\envs\mypython\ Scripts is placed at the front of the Path variable value, and after confirmation, test whether python and pip are successfully installed and configured in cmd, as shown in the figure below.
insert image description here
insert image description here
        Then open cmd under the E:\algorithm123 folder where the algorithm123.py script file is located , and enter the following command:pyinstaller -F algorithm23.pyThere are more under the folder - pycache__, build and dist folders and algorithm123.spec file, in which there is a packaged algorithm123.exe in dist

insert image description here
insert image description here

2.3.2 cmd calls the exe packaged by the 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 whether the packaged algorithm123.exe can run successfully, and enter the following command: , the cmd window algorithm123.exe E:\异常\异常.txt E:\algorithm123ExeResult\123456789exe.txtdisplays the correct execution result, and at the same time, the E:\algorithm123ExeResult file The 123456789exe.txt file is also successfully generated under the folder , as shown in the figure below.
insert image description here
insert image description here

2.3.3 C# simulates cmd to call the packaged exe of the external py script (pass in parameters with path)

        Add a Button again in the Form1 form in the C# Windows form application whose project name is InvokeQQ, change the Text property of the Button to Invokealgorithm123.exe, double-click the Button, and enter the following code in the Click event function of the Button to Call the external py script to package the exe (pass in parameters with different paths), and then click the green button above to run, and the running result is shown in the figure below.

Process cmd = new Process();
cmd.StartInfo.FileName = @"E:\algorithm123\dist\algorithm123.exe";
cmd.StartInfo.UseShellExecute = false; //此处必须为false否则引发异常
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.WorkingDirectory = "E:\\algorithm123\\dist\\";
cmd.StartInfo.CreateNoWindow = true;//不显示命令行窗口
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
string path1 = "E:\\异常\\异常.txt", path2 = "E:\\algorithm123ExeResult\\123456exe.txt";
cmd.StartInfo.Arguments = path1 + " " + path2;
cmd.Start();
MessageBox.Show("调用外部Python脚本打包exe执行文件复制成功!");

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/jing_zhong/article/details/115552400