如何解决通过在 C++ Builder 中编写新函数来转换代码
下面的程序运行良好,但在每个函数中重复相同的四行。把它变成一个函数,然后直接用值调用它。不需要变量。
void __fastcall TfrmMain::Num1()
{
String name = GetCurrentDir() + "\\first.exe";
if(FileExists(name))
{
ShellExecute(NULL,L"runas",name.c_str(),NULL,SW_SHOWNORMAL);
}
else
{
Message();
}
}
void __fastcall Main::Num2()
{
String name = GetCurrentDir() + "\\second.exe";
if(FileExists(name))
{
ShellExecute(NULL,SW_SHOWNORMAL);
}
else
{
Message();
}
}
void __fastcall Main::Num3()
{
String name = GetCurrentDir() + "\\third.exe";
if(FileExists(name))
{
ShellExecute(NULL,SW_SHOWNORMAL);
}
else
{
Message();
}
}
解决方法
您需要编写一个以 name
作为参数的函数,因此我已经提供了一个示例来说明它的外观。
我删除了文件是否存在的检查,因为这不是唯一可以执行它的原因,即使文件是可执行的,由于多种原因,它仍然可能无法执行。相反,只需尝试执行它然后调查返回值。您需要将其转换为 int
,如果 int
大于 32,则表示成功。
示例:
bool __fastcall RunAs(String name) {
name = GetCurrentDir() + "/" + name;
auto hInst = ShellExecute(nullptr,_T("runas"),name.c_str(),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"); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。