C++Builder Tips


アプリケーション・二重起動の防止


//-------------------------------------------------------------------
//  Unit1.h
//-------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE 管理のコンポーネント
  void __fastcall FormCreate(TObject *Sender);
  void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
private:
 
 HANDLE hMutex; // ユーザー宣言
public: // ユーザー宣言
  __fastcall TForm1(TComponent* Owner);
};

//-------------------------------------------------------------------
//  Unit1.cpp
//-------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
  hMutex = OpenMutex(MUTEX_ALL_ACCESS, false, Application->ExeName.c_str());
  if (hMutex != 0){ // 既にある?
    ShowMessage("既に起動されています。");
    CloseHandle(hMutex);
    Application->Terminate();
    return;
  }
  hMutex = CreateMutex(NULL, true, Application->ExeName.c_str());
}
//-------------------------------------------------------------------

void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
  if (hMutex != NULL){
    ReleaseMutex(hMutex);
    hMutex = NULL;
  }
}


DownLoad bcbtips002.lzh 4KB(BCB5)