如何只运行一个应用程序实例 [英] How to Run Only One Instance of Application

查看:129
本文介绍了如何只运行一个应用程序实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序使用套接字连接从另一个应用程序发送和接收数据。在创建套接字时,它使用端口4998。

I have a application which uses socket connection to send and receive data from another application. While creating socket it uses the port 4998 .

这是我的问题所在。一旦我启动我的应用程序套接字开始使用端口4998.所以,如果我想再次执行应用程序,我得到套接字绑定错误。

That is where my problem lie. Once I start my application the socket starts using port 4998. So if I want to execute the application again then I get socket binding error.

所以我想限制我的应用程序实例到一。这意味着如果应用程序已经在运行,有人尝试通过单击exe或快捷图标再次运行应用程序,它不应该运行程序,而应该将现有的应用程序带到顶端。

So I want to limit my application instance to one. That means if the application is already running and some one tries to run the application again by clicking the exe or shortcut icon it shouldn't run the program, instead it should bring the existing application to the Top.

推荐答案

您可以使用命名的互斥体。

You may used named mutex.

代码示例来自文章< a>:

Code sample from the article:

WINAPI WinMain(
  HINSTANCE, HINSTANCE, LPSTR, int)
{
  try {
    // Try to open the mutex.
    HANDLE hMutex = OpenMutex(
      MUTEX_ALL_ACCESS, 0, "MyApp1.0");

    if (!hMutex)
      // Mutex doesn’t exist. This is
      // the first instance so create
      // the mutex.
      hMutex = 
        CreateMutex(0, 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;
}

这篇关于如何只运行一个应用程序实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆