Solved

For viktornet

Posted on 1999-01-23
26
240 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 13
  • 12
26 Comments
 
LVL 10

Accepted Solution

by:
viktornet earned 70 total points
ID: 1363007
No problem...

Thank you!
0
 
LVL 2

Author Comment

by:SupWang
ID: 1363008
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
ID: 1363009
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Author Comment

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

Expert Comment

by:viktornet
ID: 1363011
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
ID: 1363012
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
ID: 1363013
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
ID: 1363014
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
ID: 1363015
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
ID: 1363016
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
ID: 1363017
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
ID: 1363018
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
ID: 1363019
I'll send the application tomorrow, I promise, okay?
0
 
LVL 2

Author Comment

by:SupWang
ID: 1363020
OK, thank you very much.
0
 
LVL 5

Expert Comment

by:heathprovost
ID: 1363021
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
ID: 1363022
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
ID: 1363023
Sorry for the delay SupWang :(

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

Author Comment

by:SupWang
ID: 1363024
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
ID: 1363025
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
ID: 1363026
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
ID: 1363027
Ok, I will put the code in a demo app, and send it here...
0
 
LVL 10

Expert Comment

by:viktornet
ID: 1363028
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
ID: 1363029
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
ID: 1363030
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
ID: 1363031
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
ID: 1363032
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Hello everybody This Article will show you how to validate number with TEdit control, What's the TEdit control? TEdit is a standard Windows edit control on a form, it allows to user to write, read and copy/paste single line of text. Usua…
In my programming career I have only very rarely run into situations where operator overloading would be of any use in my work.  Normally those situations involved math with either overly large numbers (hundreds of thousands of digits or accuracy re…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

752 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