函数原型:
__drv_preferredFunction("CreateProcess","Deprecated. See MSDN for details")
WINBASEAPI
UINT
WINAPI
WinExec(__in LPCSTR lpCmdLine,__in UINT uCmdShow);
preferred : 更好的
__drv_preferredFunction("CreateProcess", "Deprecated. See MSDN for details")
是 Windows 驱动开发中用于静态代码分析工具(如 PREfast for Drivers)的注解,主要作用是标记特定函数已被弃用,并推荐使用替代函数(此处为 CreateProcess
)。
WinExec
是 Windows API 中的一个函数,主要用于执行外部应用程序或命令,但其设计初衷是为兼容早期的 16 位 Windows 系统,现代开发中已被 CreateProcess
取代。以下是其核心解析:
⚙️ 函数作用
WinExec
用于启动一个外部可执行程序(.exe
)或命令行命令,并控制其窗口的显示状态。它通过简单的参数实现快速调用,适合基础场景,但功能较为有限。
示例1:
(1)
#include <windows.h>int main() {// 打开记事本(正常窗口)UINT ret = WinExec("notepad.exe", SW_SHOW);// 检查返回值if (ret <= 31) {// 处理错误(例如文件未找到)}return 0;
}
(2)
#include <Windows.h>int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,PSTR nCmdLine,int iCmdShow) {WinExec("calc.exe", SW_SHOW);return 0;
}
功能:打开记事本
(3)
WinExec("Notepad.exe", SW_HIDE);
//会出现在任务管理器中,但不会显示在任务栏。
示例2:
运行ScreenToGif.exe:
#include <Windows.h>
#include <stdlib.h>#include <iostream>
#include "tchar.h"
int main(int argc, char* argv[]) {int res = WinExec("E:\\ScreenToGif\\ScreenToGif.exe", SW_SHOW);std::cout << res<<'\n';if (res == 0) {std::cout << "系统内存或资源不足";}else if (res == ERROR_BAD_FORMAT) {std::cout << ".EXE文件格式无效";}else if (res == ERROR_FILE_NOT_FOUND) {std::cout << "指定的文件没有找到";}else if (res == ERROR_PATH_NOT_FOUND) {std::cout << "指定的路径没有找到";}return 0;
}
注意:路径中是\\
同理:
打开网易词典
int res = WinExec("E:\\网易有道词典\\Dict\\YodaoDict.exe", SW_SHOW);
打开指定的txt文件
int res = WinExec("notepad.exe D:\\2.txt", SW_SHOW);
这样也可以:
std::string str("notepad.exe D:\\work\\版本\\1.0.1\\OfficeAssistant2.0\\Debug\\license.txt");int res = WinExec(str.c_str(), SW_SHOW);
这样也可以:
QString str1("notepad.exe D:\\work\\learn_git\\Git\\2.txt");int res = WinExec(str1.toStdString().c_str(), SW_SHOW);
这样也可以:
QString中文乱码_qstring 中文_Coder-LiyG的博客-CSDN博客
QString str1=QString::fromLocal8Bit("notepad.exe D:\\work\\版本\\1.0.1\\OfficeAssistant2.0\\Debug\\license.txt");QByteArray by = str1.toLocal8Bit();int res = WinExec(str1.toLocal8Bit().constData(), SW_SHOW);