Solved

Creating a Single instance of an Application

Posted on 2004-08-03
10
470 Views
Last Modified: 2010-04-04
Hi

Up until now I have been using the following code to create a single instnce of my apps, but for some unknown reason it does not seem to work:-s. I will stop a second instnce from beeing created but will not bring the from forward. can anyone tell me what I am do wrong?

program PGLIWMan;

uses
  Forms,windows,
  VTDevManFM in 'VTDevManFM.pas' {ManFRM},
  VTGUITypes in '..\VTGUITypes.pas',
  TDeviceManager in '..\TDeviceManager.pas',
  CommonRoutines in 'G:\MyDocs\Delphi Source\Useful\CommonRoutines.pas';

{$R *.RES}

var
  Hmutex:Thandle;

begin
  HMutex:= CreateMutex(nil,false,'ManFRM');
  if WaitForSingleObject(hmutex,0) <> wait_TimeOut then
  begin
    Application.Initialize;
    Application.Title := 'VT Manager';
    Application.CreateForm(TManFRM,ManFRM);
    Application.Run;
  end
  else
  begin
    setForegroundWindow(Hmutex);
  end;
end.

I am using Delphi 5, drop me a line if you want more info
0
Comment
Question by:GTwoD
10 Comments
 
LVL 12

Expert Comment

by:esoftbg
ID: 11706414
0
 
LVL 17

Accepted Solution

by:
Wim ten Brink earned 150 total points
ID: 11706464
The HMutex is not a Windows form handle but a Mutex handle. You need a completely different solution instead... Basically, you need some kind of inter-process communications to tell the other applications to show itself. Perhaps by just using FindWindow to find the other mainform but in some more complex situations, you might need some different technique instead.

You posted this twice, btw...
0
 
LVL 12

Expert Comment

by:esoftbg
ID: 11707056
program PGLIWMan;

uses
  Forms,
  SysUtils,
  Windows,
  Messages,
  VTDevManFM in 'VTDevManFM.pas' {ManFRM};

{$R *.res}

var
  hFileMap, Handle:    Cardinal;
  FMapPt:              Pointer;

begin
  hFileMap := CreateFileMapping($FFFFFFFF,     // $FFFFFFFF get's memory file
                                nil,           // no security attributes
                                PAGE_READWRITE,// read/write access
                                0,             // size: high 32-bits
                                2048,          // size: low 32-bits
                                'Q_21080749'); // name of map object
  if (GetLastError = ERROR_ALREADY_EXISTS) then
  begin
    if (ParamCount > 0) then
    begin
      FMapPt := MapViewOfFile(hFileMap, FILE_MAP_WRITE, 0, 0, 0);
      if FMapPt <> nil then
      begin
        Handle := Cardinal(FMapPt^);
        if FileExists(ParamStr(1)) then
        StrCopy(Pointer(Integer(FMapPt)+4), PChar(ParamStr(1)));
        UnmapViewOfFile(FMapPt);
        SendMessage(Handle, WM_USER+432, 0, 0);
      end;
    end;
    CloseHandle(hFileMap);
    Exit;
  end;

  Application.Initialize;
  Application.Title := 'Single Instance Application';
  Application.CreateForm(TManFRM, ManFRM);
  Application.Run;
  CloseHandle(hFileMap);
end.

//........

unit VTDevManFM;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TManFRM = class(TForm)
    Edit1: TEdit;
  private   { Private declarations }
    procedure GetFileName(var Msg : TMessage); message WM_USER + 432;
  public    { Public declarations }
  end;

var
  ManFRM: TManFRM;

implementation

{$R *.dfm}

procedure TManFRM.GetFileName(var Msg : TMessage);
var
  hFileMap: Cardinal;
  FMapPt: Pointer;
  AryChar2: Array[0..2043] of Char;
begin
  hFileMap := OpenFileMapping(FILE_MAP_WRITE, False, 'Q_21080749');
  FMapPt := MapViewOfFile(hFileMap, FILE_MAP_WRITE, 0, 0, 0);
    if (FMapPt <> nil) then
    begin
      StrCopy(@AryChar2[0],Pointer(Integer(FMapPt)+4));
//      OpenFile(AryChar2);  {OpenFile is your apps procedure to open files}
      UnmapViewOfFile(FMapPt);
    end;
  CloseHandle(hFileMap);
end;

end.
0
ScreenConnect 6.0 Free Trial

Want empowering updates? You're in the right place! Discover new features in ScreenConnect 6.0, based on partner feedback, to keep you business operating smoothly and optimally (the way it should be). Explore all of the extras and enhancements for yourself!

 
LVL 2

Assisted Solution

by:DarkCore_
DarkCore_ earned 50 total points
ID: 11712873
Another way is to search a Window in Windows with the same name as yours.

Edu
0
 
LVL 1

Author Comment

by:GTwoD
ID: 11713047
Hi thanks for the responses

Workshop_alex do you have example of the code what you taled about?

0
 
LVL 1

Author Comment

by:GTwoD
ID: 11713064
Another point the code for bring the window forward has worked before in other apps, but not now any ideas?
 
0
 

Assisted Solution

by:HotRod40
HotRod40 earned 100 total points
ID: 11716476
You may want to try this code.  This searches for a Window using the application caption and if it locates the window then another window is not launched.  This only allows for a single instance to open at a time.

This snippet is from the project source file...

{$R *.RES}

var
  HWND: THandle;

//Stops the program opening more than once
begin
HWND := FindWindow('TForm1', 'Project1');
  if HWND = 0 then
    begin
       Application.Initialize;
       Application.Title := 'Project1';
       Application.CreateForm(TForm1, Form1);
       Application.Run;
    end
  else
    SetForeGroundWindow(HWND);


Hope this helps,

Hotrod40
0
 
LVL 1

Author Comment

by:GTwoD
ID: 11720526
Hi all realised with a couple of yours help what I did wrong the

I like the look of Hotrod's suggestion it is simple and effective, but it did not stop muliple instances

but it did inspire me write my own...


var
  Hmutex:Thandle;
  HWindow:Thandle;

begin
  HMutex:= CreateMutex(nil,false,'ManFRM');
  HWindow:= FindWindow('TManFrm');
  if WaitForSingleObject(hmutex,0) <> wait_TimeOut then
  begin
    Application.Initialize;
    Application.Title := 'VT Manager';
    Application.CreateForm(TManFRM,ManFRM);
    Application.Run;
  end
  else
  begin
    setForegroundWindow(HWindow);
  end;
end.


So I have split the point to those who has suggested FindWindow.
0
 
LVL 1

Author Comment

by:GTwoD
ID: 11720553
Repost...(Sorry)

var
  Hmutex:Thandle;
  HWindow:Thandle;

begin
  HMutex:= CreateMutex(nil,false,'ManFRM');
  //forgot to add nil as paramtre
  HWindow:= FindWindow('TManFrm',nil);
  if WaitForSingleObject(hmutex,0) <> wait_TimeOut then
  begin
    Application.Initialize;
    Application.Title := 'VT Manager';
    Application.CreateForm(TManFRM,ManFRM);
    Application.Run;
  end
  else
  begin
    setForegroundWindow(HWindow);
  end;
end.
0
 
LVL 6

Expert Comment

by:bpana
ID: 11721540
a better approach would be:

  // Will try to create a named mutex
  CreateMutex(nil, false, ManFRM);
  // if it failed then there is another instance running
  if GetLastError = ERROR_ALREADY_EXISTS then begin
    // There is an error, so it exist another ManFRM instance running
    // Send all windows our custom message - only our other
    // instance will recognise it, and restore itself
    SendMessage(HWND_BROADCAST, RegisterWindowMessage('ManFRM'), 0, 0);
    Halt(0);
  end;

  Application.Initialize;
  Application.Title := 'VT Manager';
  Application.CreateForm(TManFRM,ManFRM);
  Application.Run;

0

Featured Post

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
In this tutorial I will show you how to use the Windows Speech API in Delphi. I will only cover basic functions such as text to speech and controlling the speed of the speech. SAPI Installation First you need to install the SAPI type library, th…
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question