Powerbasic Museum 2020-B

IT-Consultant: Charles Pegge => OxygenBasic Examples => Topic started by: Chris Chancellor on January 31, 2019, 10:53:52 PM

Title: Program that allow only 1 instance to run
Post by: Chris Chancellor on January 31, 2019, 10:53:52 PM
Hello All

If you wish to restrict a program to be executed only once, you can make use of
Mutex  to check occurence of the program in memory.

Here's an example that if you run the same program more one time, then an error message
will appear and prevent it from running a second time


'====================================================================
'  Detect whether there is another instance of running
'  this program in memory using the Mutex method
'  Det_ProgExist.o2bas

$ filename "Det_ProgExist.exe"

uses rtl64
uses O2Common
uses dialogs
' #lookahead   


' Equates
% IDC_TEXTBOX1     = 1001
% IDC_TEXTBOX2     = 1002
% IDC_LABEL1          = 1003
% IDC_BUTTON1      = 1006
%  IDC_ExitBtn         = 1008   

  sys  hDlg , hMutex




'=====================================
sub winmain()
Local zMutex AS string

  zMutex = "UniqueProgID"

   'Create mutex
   hMutex = CreateMutex(BYVAL NULL, 0, zMutex)
  IF GetLastError = ERROR_ALREADY_EXISTS THEN
       mbox " Program already running -- we cannot allow another instance to run ", 0
       EXIT Sub
END IF   
         
  Dialog( 151, 118, 201, 133, "Single Instance program",
          WS_VISIBLE or DS_SETFONT,
          8, "MS Sans Serif" ,  WS_EX_DLGMODALFRAME OR WS_EX_TOPMOST)

  EDITTEXT("TextBox 1", IDC_TEXTBOX1, 10, 5, 55, 30 )

  EDITTEXT("TextBox 2", IDC_TEXTBOX2, 10, 45, 55, 30 )


  LText( "Label 1 ", IDC_LABEL1, 95, 5, 65, 30)

  PushButton( "Button1" , IDC_Button1, 125, 45, 50, 20)

  PushButton( "Exit" , IDC_ExitBtn, 10, 95, 35, 20)

  CreateModalDialog( null, @DlgProc, 0) 

End Sub




=============================================
function DlgProc( sys hDlg, uint uMsg, sys wParam, lParam ) as int callback

  select case uMsg
 
    case WM_INITDIALOG
     

    case WM_COMMAND
      select case loword(wParam)

       case IDC_Button1
                    mbox " Button 1 is clicked"

        case IDC_ExitBtn
                EndDialog( hDlg, null )

      end select

     
    case WM_CLOSE
         '  Remove the Mutex handle
           CloseHandle(hMutex)
           EndDialog( hDlg, null )
               
  end select

  return 0
end function




==============================================
'MAIN CODE start
winmain()