Easiest way to find previous instance of an application - delphi

I have rewritten a VB6 application in Delphi. It should have only one instance running. How can I do this with minimum of code?
In VB6 we just have to use one single line of code
>
If App.PrevInstance Then
'Take some action
End If
On goggling I did find a solution but it is very length and we have to mess with .drp file.
I do not want to do that.
I want something simpler.

I have some code along the lines of:
var
AppMutex: THandle;
{ .... }
initialization
// Create the mutex
AppMutex := CreateMutex(nil, True, 'MY-APPLICATION-NAME');
if (AppMutex = 0) or (GetLastError = ERROR_ALREADY_EXISTS) then
begin
MessageDlg('My application is already running on this computer.'#13#10+
'You should close the other instance before starting a new one.',mtError,
[mbOK],0);
Halt;
end;
finalization
// Close the mutex
CloseHandle(AppMutex);
but I'm sure the answers in the thread that #mghie linked to are more helpful/richer features!
Edit: Note you can make this into a small unit in it's own right, then just use that unit in your project(s).

Note that in many cases, the user's expecation will be that launching the second instance results in the first instance being restored and brought to the foreground. Don't expect users to understand the difference between restoring a minimized/hidden app and launching from a shortcut or start menu.

In my experience one cannot decide in general wether an application my be started twice or not. It may be for instance perfectly valid to start the same application if it is started in another folder or under another user account or whatever. On the other hand it might be the case that two different applications may not run together if they are started in the same folder or so.
So besides the different approaches with mutexes and semaphores and handling race conditions, it is the wise selection of the mutex's or semaphore's name that handles the above combinations appropriately.
If an application may not run twice at all, take a GUID like name. You can even use the exe's filename if you can ignore that someone might rename it.
Restricting the one-time-start on a specific folder, you can take the exe path into account, but be aware that due to mappings different pathes may end up at the same exe.

Related

How does this `if not` statement work without parentheses in a new service application?

When creating a new Windows Service in Delphi, it inserts the following:
if not Application.DelayInitialize or Application.Installing then
Application.Initialize;
The author didn't bother including parentheses, so I'm trying to wrap my head around this. It translates to:
if (not Application.DelayInitialize) or Application.Installing then
Application.Initialize;
From what I understand, if both Application.DelayInitialize and Application.Installing are True, then it will go ahead and Initialize the service application. I don't understand why it would be initialized in this scenario - I'm pretty sure it shouldn't be initialized.
Can someone give me some clarification what I'm looking at here?
On a side note, I would never need to enable DelayInitialize as there's no need to be concerned with Server 2003. I would just like to understand what this code is actually meant to do the way it's written.
As the comment inserted in the project source when you create a service application explains, DelayInitialize exists for a specific reason: the requirement to call StartServiceCtrlDispatcher before CoRegisterClassObject. Whether you would need to set it or not, I presume, would really depend on if you need to call CoRegisterClassObject, not if you're targeting server 2003 or not (*). IOW, I wouldn't expect that comment to be updated with every new server version. YMMV, testing might be required.
The implied design here is that you use System.InitProc to call CoRegisterClassObject (**), similar to how the CoInitializeEx call is made by ComObj.pas. InitProc is called from Vcl.Forms.Application.Initialize which is called from Vcl.SvcMgr.TServiceApplication.Initialize.
Now, when Vcl.SvcMgr.TServiceApplication.Installing returns true, that means StartServiceCtrlDispatcher will not to be called. Because the main thread is not going to connect with the service control manager. Instead it will either install or uninstall services and then exit. Then the need for any delayed initialization will become void and in fact a delayed initialization cannot run since no service thread will run (***).
And so this is why the expression is written the way it is, there are no forgotten/missing parenthesis.
(*) D2007 has the comment at which time 2003 R2 is the last server.
(**) From the comment in the project source:
Windows 2003 Server requires StartServiceCtrlDispatcher to be called before CoRegisterClassObject, which can be called indirectly by Application.Initialize.
(***) This is where a delayed initialization is called, guarded by a flag in case there is more than one service in the executable.

Delphi : force unload injected module

i use this code to determine if a specific module has been injected to my application's process
(i use it to prevent some Packet Sniffer Softwares)
Var
H:Cardinal;
Begin
H:= GetModuleHandle('WSock32.dll');
if H >0 then FreeLibrary(H);
end;
the problem is when i call Freelibrary it do nothing !
i don't wanna show message then terminate the application i just want to unload the injected module silently
thanks in advance
Well, first of all I'll attempt to answer the question as asked. And then, I'll try to argue that you are asking the wrong question.
Modules are reference counted. It's possible that there are multiple references to this module. So, keep calling FreeLibrary:
procedure ForceRemove(const ModuleName: string);
var
hMod: HMODULE;
begin
hMod := GetModuleHandle(PChar(ModuleName));
if hMod=0 then
exit;
repeat
until not FreeLibrary(hMod);
end;
If you were paranoid you might choose to add an alternative termination of the loop to avoid looping indefinitely.
I don't really know that this will work in your scenario. For instance, it's quite plausible that your process links statically to WSock32. In which case no amount of calling FreeLibrary will kick it out. And even if you could kick it out, the fact that your process statically linked to it probably means it's going to fail pretty hard.
Even if you can kick it out, it seems likely that other code in your process will hold references to functions in the module. And so you'll just fail somewhere else. I can think of very few scenarios where it makes sense to kick a module out of your process with complete disregard for the other users of that module.
Now, let's step back and look at what you are doing. You are trying to remove a standard system DLL from your process because you believe that it is only present because your process is having its packets sniffed. That seems unlikely to be true.
Since you state that your process is subject to packet sniffing attack. That means that the process is communicating over TCP/IP. Which means that it probably uses system modules to carry out that communication. One of which is WSock32. So you very likely link statically to WSock32. How is your process going to work if you kill one of the modules used to supply its functionality?
Are you quite sure that the presence of WSock32 in your process indicates that your process is under attack? If a packet sniffer was going to inject a DLL into your process, why would it inject the WSock32 system DLL? Did you check whether or not your process, or one of its dependencies, statically links to WSock32?
I rather suspect that you've just mis-diagnosed what is happening.
Some other points:
GetModuleHandle returns, and FreeLibrary accepts an HMODULE. For 32 bit that is compatible with Cardinal, but not for 64 bit. Use HMODULE.
The not found condition for GetModuleHandle is that the return value is 0. Nowhere in the documentation is it stated that a value greater than 0 indicates success. I realise that Cardinal and HMODULE are unsigned, and so <>0 is the same as >0, but it really makes no sense to test >0. It leaves the programmer thinking, "what is so special about <0?"

What may and don't I may do in FormCreate()?

I think this must be a FAQ, but googling hasn't really helped.
What may I do - and may do not - in FormCreate()?
I am wondering if all of the form's child controls are fully created and available for access, etc.
The reason I ask is that I stumbled over an old project where my FormCreate() simply consists of
Sleep(1000);
PostMessage(Handle, UM_PROGRAM_START, 0, 0);
It seems that I want to "wait a bit" and then do some initialization "when things have settled down" ...
Surely I had a reason for it at the time(?), but, in the absence of an enlightening comment I am unable to recall why I felt that to be necessary.
Can anyone state, or reference a link which states, any restrictions on what one may do in FormCreate()?
[Update] I think thta DavidHefferman found the solution when he wrote "the application starts pumping messages. That happens when you call Application.Run in your .dpr file".
I guess that I wasn't concerned about a single form. For instance, my main form wants to do somethign with my config/options form at start up, so obviously would have to wait until it is created.
Here's a typical .DPR from one of my projects ...
Application.Initialize;
Application.CreateForm(TGlobal, Global);
Application.MainFormOnTaskbar := True;
Application.CreateForm(TMainForm, MainForm);
Application.CreateForm(TLoginForm, LoginForm);
Application.CreateForm(TConfigurationForm, ConfigurationForm);
//[snip] a bunch of other forms ...
Application.Run();
So, it makes sense for my app's mainForm.CreateForm() to send a UM_APPLICATION_START to itself which it won't process until all forms are created & initialized (or, I could just call the fn() which the message triggers from my .DPR after Application.Run() is called; but I prefer the message as it is more obvious - I rarely look at my .DPR files).
There's no definitive documentation giving the list of all the things you can do and connot do in a form's OnCreate.
As for whether or not the .dfm file has been processed and all the form's owned components created, yes they have.
I wouldn't place much store in the code you have found. Calling Sleep during start up, to make the main thread wait, is absolutely not good practice. If the code wanted to wait for another thread it could block for that thread, or wait to get a message from that thread. This just looks like code that got put in by someone who didn't understand what he/she was doing. And the code never got removed.
The other line of code is reasonable:
PostMessage(Handle, UM_PROGRAM_START, 0, 0);
Because this message is posted, it won't get processed until the application starts pumping messages. That happens when you call Application.Run in your .dpr file. Which means that everything related to the creation of you main form happens before that message is pulled off the queue.
I wouldn't put to much initialization code in FormCreate, instead I would place it into a separate function, like
fm := TForm.Create;
fm.Init;
The problem is, an exception thrown in the FormCreate() procedure is not re-thrown (there is only a MessageBox). That means, your code keeps running, although the form is not initialized correctly.
You may do whatever you want in the FormCreate. But there is no message handler to play with, that's all. In general I would create dependent objects in the FormCreate and free them in the FormDestroy. I would also try to avoid time consuming initialization routines.

Add code before initialization of units in Delphi

Is there a place where I can add code that will be executed before unit initialization?
The reason I want to do this is I need to change the DecimalSeparator, this has to be done before the initialization of some units. I have put it in the project source, before Application.Initialize but it is too late by then.
As I see it the only choice I have is to put it in the initialization of the unit that needs the DecimalSeparator to be changed, is this the case?
Thanks in advance for any advice.
Initialization order in Delphi is deterministic: units get initialized in the same order as the compiler compiled them, and finalized in the reverse order. The compiler starts at the top of the DPR's uses clause and works its way down, and for each unit it finds, it does the same thing recursively: start at the start of the uses clause, try to compile each used unit that isn't already compiled, then compile the current unit. So if you can get your unit in before any of the other ones get compiled, then it will get initialized first.
If you want to make sure it gets executed first, make a new unit, put your changes in that unit's initialization block, and then make sure it ends up in the DPR before any of the units that will depend on the changes. You might even want to make it the first unit, unless you have other "must be first" units there already, such as replacement memory managers.
Put it into the initialization section of the first unit in your project uses list, that way it will be executed prior to any other initialization code.
A word of warning here.
I've got an application running on the desktop of a logged in user and IN THE MIDDLE of testing the app the DecimalSeparator changed for me, without me restarting the application.
I used to set the
DecimalSeparator := '.';
once in the FormCreate() code, but that seems not the be enough. So now I set it once every time before I use my FormatFloat() function (used only in one place in my application).
I do not know WHY this happens, but probably there are some system-wide parameter changes happening, that reset the char to ',' on my system.
The best way to avoid this is probably to set the decimal separator in windows configuration to '.' to avoid strange problems...

Need a way to periodically log the call stack/stack trace for EVERY method/procedure/function called

I'm working on a very large application where periodically I'd like to log the ENTIRE call stack up until the current execution point (not on an exception). The idea here is that I want a map of the exact code path that led me to the point that I am. I have been working with madExcept, tooled around with jclDebug and while I can get some of the call stack, I can't seem to get EVERY method/procedure/function call that is made in the application to show up in the log.
I've got stack frames turned on, debug info, etc enabled on the project. I even tried turning on stack frames on individual methods that weren't getting included in the call stack to no avail.
Is what I'm trying to do even possible? I'm really trying to avoid having to add logging code all over our millions of lines of code in order to log the code path.
I use JCLDebug from the JCL to do just this.
The following will get the call stack for the current location and return it as a string.
function GetCurrentStack: string;
var
stackList: TJclStackInfoList; //JclDebug.pas
sl: TStringList;
begin
stackList := JclCreateStackList(False, 0, Caller(0, False));
sl := TStringList.Create;
stackList.AddToStrings(sl, True, True, True, True);
Result := sl.Text;
sl.Free;
stacklist.Free;
end;
To make this work as expected, you must enable one of supported ways for Debug Information for JCL such as:
Turbo Debugger Information
JDBG Files (Generated from the MAP Files)
JBDG Files Inserted into the EXE.
I recently switched between JDBG files inserted into the EXE to just shipping the external JDBG files as it was easier to maintain.
There are also routines that are useful for tracing such as:
function ProcByLevel(Level : Integer) : String;
This allows you to determine the current method/procedure name looking back in the call stack "N" number of levels.
You can use madExcept - it includes a method named GetThreadStackTrace. MadExcept is free for non-commercial use and definitely worth the price otherwise.
From the responses and comments to other answers it sounds like you need a CALL LOG, not a CALL STACK. The information you want simply isn't present in a call stack.
In which case I suggest you investigate a tool such as SmartInspect or AQ Time. Of the two I think SmartInspect is most likely to be relevant. AQ Time is more of an interactive profiling tool, where-as SmartInspect has facilities specifically for remote inspection.
When you return from a method it is removed from the stack. So presumably your Partial call stack is every method that has not yet returned?
e.g.
DoSomething
begin
MiniSubMethod
DomeSomethingMore
begin
InnerDoSomething
begin
ShowCallStack
end
end
end
I would think in this situation the call stack would be
InnerDoSomething
DoSomethingMore
DoSomething
MiniSubMethod is no longer on the stack as it returned before DoSomethingMore was called.
I think FastMM4 includes a Stack Trace so you could try that.
You would definitely need some kind of logging/stack trace instead of just the call stack.
If it is a complete trace you want, I believe a tool like SmartInspect could take you a long way.
It would require you to add logging to your code but for what you need, that would be unavoidable.
Some of its highlights
Monitor in Real-Time
High-performance live logging via TCP or named-pipes to the Console
Watch and Monitor Resources
Track variable values, session data and other application resources.
Rich Logging & Tracing
Track messages, exceptions, objects, files, database results & more.

Resources