Solved

For viktornet

Posted on 1999-01-23
26
234 Views
Last Modified: 2010-04-06
This is to split the points for my previous question "How can I maximize the Application".
viktornet, Thank for your help.  
Regards,
SupWang
0
Comment
Question by:SupWang
  • 13
  • 12
26 Comments
 
LVL 10

Accepted Solution

by:
viktornet earned 70 total points
Comment Utility
No problem...

Thank you!
0
 
LVL 2

Author Comment

by:SupWang
Comment Utility
viktornet: I am familiar with mutex. Could you modify your comment for more detail? I am not very understand. :-(
Thanks,
SupWang

0
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
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
 
LVL 2

Author Comment

by:SupWang
Comment Utility
Sorry, I wrote the wrong comment. I am not familiar with mutex.
0
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
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
 
LVL 2

Author Comment

by:SupWang
Comment Utility
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
 
LVL 2

Author Comment

by:SupWang
Comment Utility
I had never used the Mutex, and I have no more time in problem. Please tell me more about that.
0
 
LVL 2

Author Comment

by:SupWang
Comment Utility
I had never used the Mutex, and I have no more time in that problem. Please tell me more about that.

0
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
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
 
LVL 2

Author Comment

by:SupWang
Comment Utility
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
 
LVL 2

Author Comment

by:SupWang
Comment Utility
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
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
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
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
I'll send the application tomorrow, I promise, okay?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 2

Author Comment

by:SupWang
Comment Utility
OK, thank you very much.
0
 
LVL 5

Expert Comment

by:heathprovost
Comment Utility
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
 
LVL 2

Author Comment

by:SupWang
Comment Utility
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
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
Sorry for the delay SupWang :(

Do you still need me to write the app?
0
 
LVL 2

Author Comment

by:SupWang
Comment Utility
Yes, I still want to learn more. Please look at http://www.delumpa.com/tips/apps/apps5.htm . What's matter with it?
0
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
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
 
LVL 2

Author Comment

by:SupWang
Comment Utility
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
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
Ok, I will put the code in a demo app, and send it here...
0
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
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
 
LVL 2

Author Comment

by:SupWang
Comment Utility
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
 
LVL 2

Author Comment

by:SupWang
Comment Utility
Please look at my new question "How Can I separate a QuickRep from a Form"
Please help me !!!
0
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
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
 
LVL 10

Expert Comment

by:viktornet
Comment Utility
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

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

A lot of questions regard threads in Delphi.   One of the more specific questions is how to show progress of the thread.   Updating a progressbar from inside a thread is a mistake. A solution to this would be to send a synchronized message to the…
Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
This video discusses moving either the default database or any database to a new volume.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

728 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now