首页 > 解决方案 > 通过在 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();
 }
 }  

标签: c++c++builder

解决方案


您需要编写一个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"); }

推荐阅读