For viktornet

This is to split the points for my previous question "How can I maximize the Application".
viktornet, Thank for your help.  
Regards,
SupWang
LVL 2
SupWangAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
viktornetConnect With a Mentor Commented:
No problem...

Thank you!
0
 
SupWangAuthor Commented:
viktornet: I am familiar with mutex. Could you modify your comment for more detail? I am not very understand. :-(
Thanks,
SupWang

0
 
viktornetCommented:
Ok, you are familiar with mutexes, so what's the problem then? What don't you understand? Here is the code again, tell me which line of code don't u understand, ok?

interface
uses Windows;
ResourceString
  AppCantStart = 'App is already running. Can not start another copy.';
  AppTitle = 'Just an App';
implementation
const
  TEN_SECS = 10000;
var
  MutexHandle : Integer;

{...}//Your code goes here...

initialization
  MutezHandle := CreateMutex(nil, False, 'Some Mutex.');
  if WaitForSingleObject(MutexHandle, TEN_SECS) <> WAIT_OBJECT_0 then
  begin
    MutexHandle := -1;
    MessageBox(0, PChar(RSCantStart), PChar(RSTitle), MB_OK);
    Halt;
  end;
finalization
  if MutexHandle <> -1 then
    ReleaseMutex(MutexHandle);
end.

-Viktor
--Ivanov
0
Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

 
SupWangAuthor Commented:
Sorry, I wrote the wrong comment. I am not familiar with mutex.
0
 
viktornetCommented:
oh, okay then....

Here is some info in Mutexes////

I copied this right off the help file..... I hope you are satisfied with this...

You can use a mutex object to protect a shared resource from simultaneous access by multiple threads or processes. Each thread must wait for ownership of the mutex before it can execute the code that accesses the shared resource. For example, if several threads share access to a database, the threads can use a mutex object to permit only one thread at a time to write to the database.

In the following example, a process uses the CreateMutex function to create a named mutex object or open a handle of an existing mutex object.

HANDLE hMutex;  

// Create a mutex with no initial owner.

hMutex = CreateMutex(
    NULL,                       // no security attributes
    FALSE,                      // initially not owned
    "MutexToProtectDatabase");  // name of mutex

if (hMutex == NULL)
{
    // Check for error.
}


When a thread of this process writes to the database, as in the next example, it first requests ownership of the mutex. If it gets ownership, the thread writes to the database and then releases its ownership.
The example uses the try-finally structured exception-handling syntax to ensure that the thread properly releases the mutex object. The finally block of code is executed no matter how the try block terminates (unless the try block includes a call to the TerminateThread function). This prevents the mutex object from being abandoned inadvertently.

BOOL FunctionToWriteToDatabase(HANDLE hMutex)  
{
    DWORD dwWaitResult;

    // Request ownership of mutex.
 
    dwWaitResult = WaitForSingleObject(
        hMutex,   // handle of mutex
        5000L);   // five-second time-out interval
 
    switch (dwWaitResult)
    {
        // The thread got mutex ownership.
        case WAIT_OBJECT_0:
            try {
                // Write to the database.
            }

            finally {
                // Release ownership of the mutex object.

                if (! ReleaseMutex(hMutex)) {
                    // Deal with error.
                }

            break;
        }

        // Cannot get mutex ownership due to time-out.
        case WAIT_TIMEOUT:
            return FALSE;

        // Got ownership of the abandoned mutex object.
        case WAIT_ABANDONED:
            return FALSE;
    }

    return TRUE;
}

-Viktor
--Ivanov
0
 
SupWangAuthor Commented:
If my Application name/title is "TestPrg". How does I modify your code? where I put it to? (DPR or MainForm or SplashForm). Could you Please modify your code, so I can use it directly.

0
 
SupWangAuthor Commented:
I had never used the Mutex, and I have no more time in problem. Please tell me more about that.
0
 
SupWangAuthor Commented:
I had never used the Mutex, and I have no more time in that problem. Please tell me more about that.

0
 
viktornetCommented:
ok, here is the modified code so you can use it directly....

your code for the splash screen (Form) you put in the DPR.... The code for the Mutext and stuff, you put in your PAS file.... here is the code that should be in the PAS file...

interface
uses Windows;
ResourceString
AppTitle = 'TestPrg';
AppCantStart = AppTitle + ' is already running. Cannot start another copy.';
implementation
const
TEN_SECS = 10000;
var
MutexHandle : Integer;
//All of your code goes here...
initialization
MutezHandle := CreateMutex(nil,False,'You should use some strange name here.');
if WaitForSingleObject(MutexHandle,TEN_SECS) <> WAIT_OBJECT_0 then
begin
MutexHandle := -1;
MessageBox(0,PChar(RSCantStart),PChar(RSTitle),MB_OK);
Halt;
end;
finalization
if MutexHandle <> -1 then
ReleaseMutex(MutexHandle);
end.

That's all.... If you want me I can create an example project for you that will show you how to do all this... I'll include the splash screen also... Just let me know your e-mail address and I'll send it to you in a while....

Please decide whether you'll accept my answer or not... Thank you!

-Viktor
--Ivanov
0
 
SupWangAuthor Commented:
Could you add your code to Delphi Database Demo(MastApp)? Please including "PostMessage(AppWindow, WM_SYSCOMMAND, SC_RESTORE, 0)" and "SetForeGroundWindow(AppWindow)", similar to heathprovost's comment (Saturday, January 23 1999 - 11:12PM)
My e-mail is ddc@188.net.

Thanks a lot.
0
 
SupWangAuthor Commented:
I just have the D3. If you use D4, Maybe I can't open it.
Please copy these units which you modified to txt files.
0
 
viktornetCommented:
Hello Sup, I thought I'd have time, but it seems like I gotta go... I'll have to do that for you tomorrow... I'm sorry... I'll do it tomorrow some time and send the code right here...

-Viktor
--Ivanov
0
 
viktornetCommented:
I'll send the application tomorrow, I promise, okay?
0
 
SupWangAuthor Commented:
OK, thank you very much.
0
 
heathprovostCommented:
How about this one?

>>>>>>>>>CODE PASTE

program PGETPREV;

uses
  Forms, Windows, Messages,
  GETPREV in 'GETPREV.pas' {Form1};

{$R *.RES}

const
  MyApp = 'tHiS_iS_My_fUnKy_aPp_wItH_A_WeIrD_NaMe'; //Anything you want - just make it hard to duplicate
  ERROR_ALREADY_EXISTS = 183; //for some reason it is not in the windows declarations
  SEMAPHORE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or 3; //Ditto

var
  SemaphoreHandle, PrevSemaphoreHandle, PrevAppHandle: THandle;

begin
  SemaphoreHandle := CreateSemaphore(nil, Application.Handle, Application.Handle, MyApp);
    //Create semaphore with the count set to the value of this instances handle so we can get it later
  if GetLastError = ERROR_ALREADY_EXISTS then //If PrevInst is running this will be true
  begin
    PrevSemaphoreHandle := OpenSemaphore(SEMAPHORE_ALL_ACCESS, False,      MyApp);
      //Gets the handle of the semaphore created by the prev instance
    if PrevSemaphoreHandle <> 0 then //if call succeeded
    begin
      ReleaseSemaphore(PrevSemaphoreHandle, 0, @PrevAppHandle);
        //We only call this so we can get the handle of the last instance
      if IsIconic(PrevAppHandle) then
        PostMessage(PrevAppHandle, WM_SYSCOMMAND, SC_RESTORE, 0)
      else
        SetForeGroundWindow(PrevAppHandle);
          //Above should be fairly self explanatory
    end;
  end
  else
  begin
    // no prev instance we go ahead and run the app
    Application.Initialize;
    Application.CreateForm(TForm1, Form1);
    Application.Run;
    //There is no reason to destroy the semaphore now since the system will do it once our app closes
  end;
end.

>>>>>>>>>>>END CODE

This way you dont need to do find window at all and it should work without having to change your pas file at all.


Heath
0
 
SupWangAuthor Commented:
There's an article about mutex here: http://www.delumpa.com/tips/apps/apps5.htm
But it didn't work. what's the matter with it? I am not familiar with mutex.

0
 
viktornetCommented:
Sorry for the delay SupWang :(

Do you still need me to write the app?
0
 
SupWangAuthor Commented:
Yes, I still want to learn more. Please look at http://www.delumpa.com/tips/apps/apps5.htm . What's matter with it?
0
 
viktornetCommented:
The code seems okay... What didn't work when you tried to compile it? Please let me know so I can take a look at the article again and see if there is really something wrong.. k?

Are you planning to accept my answer?

btw- Don't forget to tell me where you get the compiling error so I know where to look at.

-Viktor
--Ivanov
0
 
SupWangAuthor Commented:
This code (mutex section) seems can not prevent the program run again. Could you add this code to a demo of Delphi and test it? If you want, Please give your own code to me.
0
 
viktornetCommented:
Ok, I will put the code in a demo app, and send it here...
0
 
viktornetCommented:
Hello SupWang!

The code from that article is too long and doesn't work right.. Anyway, here is my code that I tested and it works alright...

Actual;ly I have not changed anything in my DPR... Here it is...
========DPR=====
program Project1;

uses
  Windows, Forms,
  Unit1 in 'Unit1.pas' {Form1};

{$R *.RES}

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.
===========PAS=========
unit Unit1;

interface

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

type
  TForm1 = class(TForm)
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

ResourceString
  AppCantStart = 'App is already running. Can not start another copy.';
  AppTitle = 'My App';

const
  ONE_SEC = 1000;
var
  MutexHandle : integer;

initialization
   MutexHandle := CreateMutex(nil, False, 'Some stupid name for this mutex');
   if WaitForSingleObject(MutexHandle, ONE_SEC) <> WAIT_OBJECT_0 then
   begin
      MutexHandle := -1;
      Messagebox(0, PChar(AppCantStart), PChar(AppTitle), MB_OK);
      Halt;
   end;
finalization
  if MutexHandle <> -1 then
     ReleaseMutex(MutexHandle);
end.
==========
That's all you gotta do... Let me know if it's okay.. and please decided whether you are gonna accept my answer or not... :)

-Viktor
--Ivanov
0
 
SupWangAuthor Commented:
I don't want to put your code to the main form. Because that still will cause the splash form show again. Could you modify your code to a function? so I can call this function in the DPR file. and I want the function incluing "PostMessage, SetForeGroundWindow ....." (like Heath's code) I am sorry that I have no time to do this by myself. I am very busy now. :(
0
 
SupWangAuthor Commented:
Please look at my new question "How Can I separate a QuickRep from a Form"
Please help me !!!
0
 
viktornetCommented:
I'm quite busy too, but I will try to do it for you maybe tomorrow since it's the weekend.. is that okay with you?

-Viktor-
0
 
viktornetCommented:
hey SupWAng... I didn't have much time that last couple of days, but i found something indeed...

Put this in the OnCreate() OnDestroy() of your Splash form or something...

procedure TForm1.FormCreate(Sender: TObject);
begin
  if GlobalFindAtom('PROGRAM_RUNNING') = 0 then
    atom := GlobalAddAtom('PROGRAM_RUNNING')
  else begin
    MessageDlg('You have the program running all ready!!', mtWarning, [mbOK], 0);
    Halt;
  end;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  GlobalDeleteAtom(atom);
end;
0
All Courses

From novice to tech pro — start learning today.