窗口可防止多个实例代码不起作用
Windows prevent multiple instances code not working
>我正在使用 CreateEvent 来防止我的应用程序的多个实例:
CreateEvent(NULL, TRUE, FALSE, "MyEvent");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
// Do Stuff
return FALSE;
}
但是,在启动时,我注意到这不起作用:显示桌面后,我会自动运行一个批处理脚本,该脚本尝试启动程序的多个实例。批处理脚本成功,我确实可以看到多个实例。
到目前为止的调查:
- 输出调试显示每个实例都不会得到
ERROR_ALREADY_EXISTS
- ProcessExplorer.exe 显示每个实例都能够获取事件"MyEvent"的句柄。
谁能想到为什么会发生这种情况,以及我该如何解决它?
我们使用下面的函数,它位于我们的通用实用程序 DLL 中。 该方法派生自一篇Microsoft文章,该文章解释了如何在 WIN32 中防止多个实例。
#define STRICT
#include <stdheaders.h>
HANDLE ghSem;
BOOL IExist( LPSTR lpszWindowClass )
{
HWND hWndMe;
int attempt;
for( attempt=0; attempt<2; attempt++ )
{
// Create or open a named semaphore.
ghSem = CreateSemaphore( NULL, 0, 1, lpszWindowClass );
// Close handle and return NULL if existing semaphore was opened.
if( (ghSem != NULL) &&
(GetLastError() == ERROR_ALREADY_EXISTS) )
{ // Someone has this semaphore open...
CloseHandle( ghSem );
ghSem = NULL;
hWndMe = FindWindow( lpszWindowClass, NULL );
if( hWndMe && IsWindow(hWndMe) )
{ // I found the guy, try to wake him up
if( SetForegroundWindow( hWndMe ) )
{ // Windows says we woke the other guy up
return TRUE;
}
}
Sleep(100); // Maybe the semaphore will go away like the window did...
}
else
{ // If new semaphore was created, return FALSE.
return FALSE;
}
}
// We never got the semaphore, so we must
// behave as if a previous instance exists
return TRUE;
}
只需在WinMain中执行类似操作:
if( IExist("MyWindowClass") )
{
return 1;
}
当然,您可以将返回替换为当您不是第一个实例时需要执行的任何操作(例如激活现有实例)。
相关文章:
- 为什么这段代码不起作用,我该如何解决?
- 为什么这些完全相似的代码不起作用?
- 我不明白为什么我的代码不起作用并且需要更长的时间来运行
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 注释一行使代码工作,而没有它,代码不起作用
- 我的C++合并排序代码不起作用。我在这里错过了什么?
- C ++函数重新定义(代码不起作用 - 逻辑错误)
- 试图找到一个数字的平方根,但代码不起作用。C++
- 字符串代码不起作用
- 我正在努力在随机数组中查找最小值,有人知道为什么我的代码不起作用?C++
- 从 C++ 转换的 C# 代码不起作用
- 有人可以解释我,为什么我的代码不起作用吗?
- 当我使用长整型时,我的代码不起作用,它与 int 一起工作得很好
- 无法在控制面板中创建轨道栏.示例代码不起作用
- CUDA我的共享内存代码不起作用,我缺少什么
- 为什么 C++ 中的 shell 脚本代码不起作用?
- 为什么C++代码不起作用(strncpy_s)?
- 模板函数声明为 void - 代码不起作用?
- 无法弄清楚为什么这个Arduino代码不起作用?
- "check if member exists using enable_if"中修改的代码不起作用