How to open additional files in an already running application
I The following implementation is currently implemented for this:
Dpr file
var
PrevWindow : HWND;
S : string;
CData : TCopyDataStruct;
begin
PrevWindow := 0;
if OpenMutex(MUTEX_ALL_ACCESS, False, 'YourUniqueStringHere') <> 0 then
begin
PrevWindow:=FindWindow('TYourMainFormClassName', nil);
if IsWindow(PrevWindow) then
begin
SendMessage(PrevWindow, WM_SYSCOMMAND, SC_RESTORE, 0);
BringWindowToTop(PrevWindow);
SetForegroundWindow(PrevWindow);
if FileExists(ParamStr(1)) then
begin
S:=ParamStr(1);
CData.dwData:=0;
CData.lpData:=PChar(S);
CData.cbData:=1+Length(S);
SendMessage(PrevWindow, WM_COPYDATA, 0, DWORD(@CData) );
end;
end;
end
else
CreateMutex(nil, False, 'YourUniqueStringHere');
in the main module, we handle the WM_COPYDATA message:
we declare a message handler
procedure ReceiveData_Handler ( var msg : TWMCopyData ) ; message WM_COPYDATA;
procedure TForm1.ReceiveData_Handler(var msg: TWMCopyData);
begin
// Your file name is in the msg.CopyDataStruct.lpData
// Cast it to PChar();
end;
Hope it works for you.
source to share
The solution to this is also a solution to prevent more than one application from running at the same time. What you want to do is first detect that the program is already running, then pass the parameter to the running application and close.
There are several methods to determine if your application is running. After you choose the one that matches your programming settings, the next step is to submit a file to open your running program. This can be done through named pipes, messages (although messages do not work in Vista / Win7 if the application is running in a different security context), or any other IPC method .
source to share
Review the Windows DDE documentation . I am changing the DDEExec options in the registry so the wrapper correctly directs the open file to my existing application instance. The following code makes the necessary changes to the registry. Replace "AppName" with your application name (and remove the brackets).
// add the ddeexec key
if not reg.OpenKey( '\Software\Classes\<AppName>.file\shell\open\ddeexec', true ) then
raise Exception.Create( 'Error setting ddeexec key' );
try
reg.WriteString( '', 'FileOpen("""%1""")' );
finally
reg.CloseKey;
end;
// modify the command key to not include the parameter, as we don't use it
if not reg.OpenKey( '\Software\Classes\<AppName>.file\shell\Open\command', true ) then
raise Exception.Create( 'Error opening command key.' );
try
strTemp := reg.ReadString( '' );
strTemp := StringReplace( strTemp, '"%1"', '', [] );
reg.WriteString( '', strTemp );
finally
reg.CloseKey;
end;
source to share