21xrx.com
2024-09-20 00:18:30 Friday
登录
文章检索 我的文章 写文章
如何在C++中关闭先前打开的程序?
2023-07-06 06:02:00 深夜i     --     --
C++ 关闭程序 先前打开 终止进程 ExitProcess()函数

在C++中关闭先前打开的程序可能是一个相对困难的任务,但是有一些简单的方法可以帮助您完成这项工作。

首先,您可以使用Windows API来关闭先前打开的程序。Windows API提供了CloseHandle函数,它可以关闭先前打开的程序。下面是一个使用CloseHandle函数关闭进程的示例代码:


#include <Windows.h>

#include <iostream>

using namespace std;

int main()

{

  DWORD pid = 0; // Process ID

  HANDLE hProcess; // Process Handle

  pid = FindProcess("notepad.exe"); // Get the process ID of Notepad.exe

  if (pid != 0) // If the process is found

  {

    hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid); // Open the process handle

    TerminateProcess(hProcess, 0); // Terminate the process

    CloseHandle(hProcess); // Close the process handle

    cout << "Notepad.exe terminated." << endl; // Display message

  }

  else // If the process is not found

  

    cout << "Notepad.exe not found." << endl; // Display message

  

  return 0;

}

在这个例子中,我们使用FindProcess函数来检索Notepad.exe的进程ID。接下来,我们使用OpenProcess函数打开进程句柄,然后使用TerminateProcess函数终止进程。最后,我们使用CloseHandle函数关闭进程句柄。请注意,此方法需要您知道先前打开的程序的进程ID。

另一种方法是使用第三方库,例如Boost.Process。Boost.Process允许您以更高级别的方式启动和管理进程。下面是一个使用Boost.Process关闭进程的示例代码:


#include <boost/process.hpp>

#include <iostream>

namespace bp = boost::process;

using namespace std;

int main()

{

  bp::child c("notepad.exe");

  cout << "Press any key to terminate Notepad.exe..." << endl;

  getchar();

  c.terminate();

  return 0;

}

在这个例子中,我们使用Boost.Process库启动Notepad.exe,并使用child对象c来管理Notepad.exe进程。最后,我们使用terminate函数终止进程。请注意,此方法需要您使用Boost.Process库,并需要您以更高级别的方式管理进程。

总的来说,在C++中关闭先前打开的程序并不是一项简单的任务。但是,可以使用Windows API或第三方库来完成它。请根据您的需求选择合适的方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章