c++ - 通过在 C++ Builder 中编写新函数来转换代码
问题描述
下面的程序工作正常,但在每个函数中重复相同的四行。把它变成一个函数,然后直接用值调用它。不需要变量。
void __fastcall TfrmMain::Num1()
{
String name = GetCurrentDir() + "\\first.exe";
if(FileExists(name))
{
ShellExecute(NULL, L"runas", name.c_str(), NULL, NULL, SW_SHOWNORMAL);
}
else
{
Message();
}
}
void __fastcall Main::Num2()
{
String name = GetCurrentDir() + "\\second.exe";
if(FileExists(name))
{
ShellExecute(NULL, L"runas", name.c_str(), NULL, NULL, SW_SHOWNORMAL);
}
else
{
Message();
}
}
void __fastcall Main::Num3()
{
String name = GetCurrentDir() + "\\third.exe";
if(FileExists(name))
{
ShellExecute(NULL, L"runas", name.c_str(), NULL, NULL, SW_SHOWNORMAL);
}
else
{
Message();
}
}
解决方案
您需要编写一个name
作为参数的函数,因此我提供了一个示例来说明它的外观。
我已经删除了文件是否存在的检查,因为这不是唯一可以执行它的东西,即使文件是可执行的,它仍然可能由于多种原因而无法执行。相反,只需尝试执行它然后调查返回值。您需要将其转换为 a int
,如果int
大于 32,则它是成功的。
例子:
bool __fastcall RunAs(String name) {
name = GetCurrentDir() + "/" + name;
auto hInst = ShellExecute(nullptr, _T("runas"), name.c_str(),
nullptr, nullptr, SW_SHOWNORMAL);
int rv = reinterpret_cast<int>(hInst);
bool successful = rv > 32;
if(not successful) {
/*
switch(rv) {
case ERROR_FILE_NOT_FOUND: // one of the many possible errors
// do something specific to this error
break;
}
*/
Message();
}
// Make it possible for the calling functions to take action
// if running the program failed:
return successful;
}
然后您可以将成员函数更改为:
void __fastcall TfrmMain::Num1() { RunAs("first.exe"); }
void __fastcall TfrmMain::Num2() { RunAs("second.exe"); }
void __fastcall TfrmMain::Num3() { RunAs("third.exe"); }
推荐阅读
- sql - 如何比较 SQL 中的两个字符串值?
- python-3.6 - 使用 pyinstaller 将 .py 转换为 .exe 后,出现错误“没有名为 'pyproj._datadir' 的模块”
- laravel - 如何在运行时根据 id 获取剩余数量?
- delphi - 需要帮助:CodeGear.Cpp.Targets(3907,5): 错误 MSB6006: "id" exited with code 1
- json - 无法保存修改 JSON
- javascript - 如果文本显示在容器外,则隐藏文本
- c# - 是否可以参考其他编码语言来反序列化 .net DataContractSerializer xml?
- shopify - 如何更改shopify主页上的特色产品“要显示的新产品数量”?
- docker - 使用 Jenkins 和 Docker 构建时“设备上没有剩余空间”
- java - 在日志中获取关联 ID