我有一个应用程序使用套接字连接从另一个应用程序发送和接收数据.在创建套接字时,它使用端口4998.
那就是我的问题所在.一旦我启动我的应用程序,套接字开始使用端口4998.所以如果我要再次执行该应用程序,我得到套接字绑定错误.
所以我想将我的应用程序实例限制在一个.这意味着如果应用程序已经在运行,并且有一些尝试通过单击exe或快捷方式图标再次运行该应用程序,则它不应该运行该程序,而应该将现有的应用程序带到Top.
解决方法
您可以使用命名的互斥体.
article代码示例:
WINAPI WinMain(
HINSTANCE,HINSTANCE,LPSTR,int)
{
try {
// Try to open the mutex.
HANDLE hMutex = OpenMutex(
MUTEX_ALL_ACCESS,"MyApp1.0");
if (!hMutex)
// Mutex doesn’t exist. This is
// the first instance so create
// the mutex.
hMutex =
CreateMutex(0,"MyApp1.0");
else
// The mutex exists so this is the
// the second instance so return.
return 0;
Application->Initialize();
Application->CreateForm(
__classid(TForm1),&Form1);
Application->Run();
// The app is closing so release
// the mutex.
ReleaseMutex(hMutex);
}
catch (Exception &exception) {
Application->
ShowException(&exception);
}
return 0;
}