Flutter-Windows:让程序有且只有一个运行

126 阅读1分钟

实现步骤:

  1. 打开main.cpp($project\windows\runner\main.cpp)
  2. 在程序入口处定义方法
BOOL isProgramAlreadyRunning();
  1. 实现isProgramAlreadyRunning
BOOL isProgramAlreadyRunning() {
    HANDLE hMutex;
    BOOL isRunning = FALSE;
    hMutex = CreateMutex(NULL, FALSE, TEXT("Turbo+"));
    if (hMutex == NULL || ERROR_ALREADY_EXISTS == ::GetLastError())
    {
       isRunning = TRUE;
    }
    ReleaseMutex(hMutex);
    return isRunning;
}

4.在wWinMain函数下使用

int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
                      _In_ wchar_t *command_line, _In_ int show_command) {
    if(isProgramAlreadyRunning()){
        MessageBoxEx(NULL, TEXT("The program is already running!"), TEXT("Error"), MB_OK, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US));
        return FALSE;
    }
   ...
   ...
}