C#使用WinExec调用exe程序

485
2023/12/18 5:51:48
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中使用WinExec来调用exe程序可以通过使用DllImport来导入WinExec函数,然后调用它来执行指定的exe程序。

首先,需要在代码中导入System.Runtime.InteropServices命名空间,以便使用DllImport特性。

using System;
using System.Runtime.InteropServices;

public class Program
{
    [DllImport("kernel32.dll")]
    public static extern int WinExec(string fileName, int command);

    public static void Main()
    {
        string path = "C:\\path\\to\\your\\program.exe";
        int result = WinExec(path, 1);

        if (result > 31)
        {
            Console.WriteLine("The program was launched successfully.");
        }
        else
        {
            Console.WriteLine("Failed to launch the program.");
        }
    }
}

在上面的示例中,我们通过调用WinExec函数来执行指定的exe程序。WinExec函数的第一个参数是要执行的程序的路径,第二个参数是命令选项。在这里,我们将命令选项设置为1,表示显示程序窗口。

WinExec函数的返回值是一个整数,如果大于31,则表示程序启动成功。在上面的示例中,我们检查返回值并打印相应的消息。

请注意,WinExec函数已经被Microsoft标记为过时的函数。在新的C#版本中,推荐使用Process.Start方法来启动外部程序。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C#字典的容量管理策略