1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
|
//------------------------------------------------------------------------------
(* SoLuTions is an Versatile Library for Delphi -
* -
* Version alternative publiée sur "www.developpez.net" -
* Post : "[Tutoriel] Envoyer des chaînes et structures par PostMessage" -
* Post Number : 7029509 -
* Post URL = "http://www.developpez.net/forums/d1286417/environnements-developpement/delphi/tutoriel-envoyer-chaines-structures-postmessage/#post7029509"
* -
* Copyright ou © ou Copr. "SLT Solutions", (2006) -
* contributeur : ShaiLeTroll (2012) - Renommage Fichier et Correction XE2 -
* contributeur : ShaiLeTroll (2012) - Documentation Insight -
* contributeur : ShaiLeTroll (2014) - Reprise de la SLT<2012> sous C++Builder XE2/XE3 vers la SLT<2013> sous Delphi XE2
* -
* ShaiLeTroll@gmail.com -
* -
* Ce logiciel est un programme informatique servant à aider les développeurs -
* Delphi avec une bibliothèque polyvalente, adaptable et fragmentable. -
* -
* Ce logiciel est régi par la licence CeCILL-C soumise au droit français et -
* respectant les principes de diffusion des logiciels libres. Vous pouvez -
* utiliser, modifier et/ou redistribuer ce programme sous les conditions -
* de la licence CeCILL-C telle que diffusée par le CEA, le CNRS et l'INRIA -
* sur le site "http://www.cecill.info". -
* -
* En contrepartie de l'accessibilité au code source et des droits de copie, -
* de modification et de redistribution accordés par cette licence, il n'est -
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, -
* seule une responsabilité restreinte pèse sur l'auteur du programme, le -
* titulaire des droits patrimoniaux et les concédants successifs. -
* -
* A cet égard l'attention de l'utilisateur est attirée sur les risques -
* associés au chargement, à l'utilisation, à la modification et/ou au -
* développement et à la reproduction du logiciel par l'utilisateur étant -
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à -
* manipuler et qui le réserve donc à des développeurs et des professionnels -
* avertis possédant des connaissances informatiques approfondies. Les -
* utilisateurs sont donc invités à charger et tester l'adéquation du -
* logiciel à leurs besoins dans des conditions permettant d'assurer la -
* sécurité de leurs systèmes et ou de leurs données et, plus généralement, -
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. -
* -
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez -
* pris connaissance de la licence CeCILL-C, et que vous en avez accepté les -
* termes. -
* -
*----------------------------------------------------------------------------*)
unit SLT.Common.Winapi.ShellApi;
{$ALIGN ON}
{$MINENUMSIZE 4}
interface
{*$DEFINE DEBUG_SLT_SEW*}
{$IFDEF MSWINDOWS}
uses
Winapi.Windows, Winapi.ShellApi, Winapi.ShlObj, Winapi.Messages, Winapi.ActiveX,
System.Classes, System.SysUtils, System.Generics.Collections;
{$ELSE MSWINDOWS}
{$MESSAGE ERROR 'Implémentation uniquement Windows pour TSLTShellExecuteWrapper'}
{$MESSAGE ERROR 'Implémentation uniquement Windows pour TSLTProcessNotification'}
{$MESSAGE ERROR 'Implémentation uniquement Windows pour TSLTCopyDataMessenger'}
{$MESSAGE ERROR 'Implémentation uniquement Windows pour TSLTShellLink'}
{$ENDIF MSWINDOWS}
type
{ Forward class declarations }
TSLTShellExecuteWrapper = class;
TSLTProcessNotification = class;
TSLTCopyDataMessenger = class;
TSLTShellLink = class;
/// <summary>TSLTShellExecuteWrapper encapsule un appel à ShellExecute avec un passage de paramètre via message WM_COPYDATA permettant d'envoyer plus de donnée que l'on pourrait le faire en ligne de commande</summary>
/// <remarks>TSLTShellExecuteWrapper doit être utilisé de préférence par héritage pour encaspuler la gestion des pointeurs AData
/// <para>L'Appelant EST TOUJOURS responsable de la libération de AData passé à Execute ou reçu via Receive</para>
/// <para>TSLTShellExecuteWrapper est une version ouverte du TShaiExecuteProcessWithAutoLogin de la SLT<2009></para></remarks>
TSLTShellExecuteWrapper = class(TObject)
private
// Membres Privés
FWindowHandle: HWND;
FToken: TGUID;
FCallerHandle: HWND;
FReceiverHandle: HWND;
FReady: Boolean;
FAborted: Boolean;
FData: Pointer;
FDataSize: DWORD;
// Types Privés
type
TMsgDataOperation = (mdoReceiverNeedData, mdoCallerSendData);
TMsgHeader = record
Operation: TMsgDataOperation;
Token: TGUID;
DataSize: DWORD;
end;
// Méthodes Privées
function Run(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW): Boolean;
function MakeExeName(const AExeName: string): string;
function MakeParams(AStartWithData: Boolean): string;
function ReadParams(): Boolean;
function SendData(const AData: Pointer; const ADataSize: DWORD): Boolean;
function ReadData(out AData: Pointer; out ADataSize: DWORD): Boolean;
function WaitResponse(): Boolean;
procedure WndProc(var Message: TMessage);
function TryStrToHWND(const S: string; out Value: HWND): Boolean;
{$IFDEF DEBUG_SLT_SEW}
procedure OutputDebugSEW(const Msg: string); inline;
{$ENDIF DEBUG_SLT_SEW}
protected
// Méthodes Protégées
procedure AllocData(var AData: Pointer; ADataSize: Integer); virtual;
public
// Constructeurs Publiques
destructor Destroy(); override;
// Méthodes Publiques
class function Execute(const AExeName: string; const AData: Pointer = nil; const ADataSize: DWORD = 0; AShowCmd: Integer = SW_SHOW): Boolean;
class function Receive(out AData: Pointer; out ADataSize: DWORD): Boolean;
end;
/// <summary>TSLTProcessNotifyToken identifie une notification gérée par TSLTProcessNotification</summary>
TSLTProcessNotifyToken = UINT;
/// <summary>TSLTProcessNotifyListener identifie une cible écoutant les notifications gérées par TSLTProcessNotification</summary>
TSLTProcessNotifyListener = HWND;
/// <summary>TSLTProcessNotifyEvent est l'évènement émis par TSLTProcessNotification</summary>
TSLTProcessNotifyEvent = procedure(Sender: TObject; Token: TSLTProcessNotifyToken) of object;
/// <summary>TSLTProcessNotification gère un échange inter-processus</summary>
TSLTProcessNotification = class(TObject)
private
// Types Privés
type
TTokenInfo = class(TObject)
public
type
TListenerList = System.Generics.Collections.TList<TSLTProcessNotifyListener>;
strict private
FToken: TSLTProcessNotifyToken;
FListeners: TListenerList;
public
// Constructeurs Publiques
constructor Create(AToken: TSLTProcessNotifyToken);
destructor Destroy(); override;
// Propriétés Publiques
property Token: TSLTProcessNotifyToken read FToken;
property Listeners: TListenerList read FListeners;
end;
TTokenList = System.Generics.Collections.TObjectList<TTokenInfo>;
TNotificationMap = System.Generics.Collections.TDictionary<string, TSLTProcessNotifyToken>;
private
// Membres Privés
FListener: TSLTProcessNotifyListener;
FListenerName: string;
FNotifications: TNotificationMap;
FOnNotify: TSLTProcessNotifyEvent;
FTokens: TTokenList;
// Méthodes Privées
procedure WndProc(var Message: TMessage);
function GetListener(): TSLTProcessNotifyListener;
function FindToken(AToken: TSLTProcessNotifyToken): TTokenInfo;
function GetListenerName(): string;
procedure SetListenerName(const Value: string);
public
// Constructeurs Publiques
constructor Create();
destructor Destroy(); override;
// Méthodes Publiques
function RegisterNotification(const ANotificationName: string): TSLTProcessNotifyToken;
function AddListener(AListener: TSLTProcessNotifyListener; AToken: TSLTProcessNotifyToken): Boolean;
function AddListenerByName(const AListenerName: string; AToken: TSLTProcessNotifyToken): Boolean;
procedure NotifyListeners(AToken: TSLTProcessNotifyToken); overload;
function NotifyListeners(const ANotificationName: string): TSLTProcessNotifyToken; overload;
function Notify(AListener: TSLTProcessNotifyListener; AToken: TSLTProcessNotifyToken): Boolean;
function Listen(): Boolean;
// Propriétés Publiques
property Listener: TSLTProcessNotifyListener read GetListener;
property ListenerName: string read GetListenerName write SetListenerName;
property OnNotify: TSLTProcessNotifyEvent read FOnNotify write FOnNotify;
end;
/// <summary>TSLTCopyDataMessengerDataEvent est l'évènement émis par TSLTCopyDataMessenger lorsqu'il y a de données à lire</summary>
TSLTCopyDataMessengerDataEvent = function(Sender: TObject; DataSender: HWND; Data: Pointer; DataLen: NativeUInt): Boolean of object;
/// <summary>TSLTCopyDataMessenger gère un échange de données inter-processus via le message WM_COPYDATA</summary>
TSLTCopyDataMessenger = class(TObject)
private
// Membres Privés
FListenerHandle: HWND;
FListenerName: string;
FRecipientHandle: HWND;
FRecipientName: string;
FRawData: COPYDATASTRUCT;
FOnDataAvailable: TSLTCopyDataMessengerDataEvent;
// Accesseurs
function GetListenerHandle(): HWND;
function GetListenerName(): string;
procedure SetListenerName(const Value: string);
function GetRecipientName(): string;
procedure SetRecipientName(const Value: string);
// Méthodes Privées
procedure WndProc(var Message: TMessage);
function DoDataAvailable(DataSender: HWND; Data: Pointer; DataLen: NativeUInt): Boolean;
public
// Constructeurs Publiques
destructor Destroy(); override;
// Méthodes Publiques
procedure BeginWrite();
procedure WriteInteger(const Value: Integer);
procedure WriteString(const Value: string);
procedure WriteBuffer(const Data: Pointer; const DataLen: NativeUInt);
function EndWrite(): Boolean;
procedure CancelWrite();
function Listen(): Boolean;
function ReadInteger(const Data: Pointer; out Value: Integer): Integer;
function ReadString(const Data: Pointer; out Value: string): Integer;
function Seek(const Data: Pointer; Offset: NativeUInt): Pointer;
// Propriétés Publiques
property ListenerHandle: HWND read GetListenerHandle;
property ListenerName: string read GetListenerName write SetListenerName;
property RecipientHandle: HWND read FRecipientHandle write FRecipientHandle;
property RecipientName: string read GetRecipientName write SetRecipientName;
property OnDataAvailable: TSLTCopyDataMessengerDataEvent read FOnDataAvailable write FOnDataAvailable;
end;
/// <summary>TSLTShellLink encapsule l'utilisation de l'interface IShellLink</summary>
TSLTShellLink = class(TObject)
public
class function ExtractTarget(const AShellLinkFileName: TFileName): TFileName;
end;
implementation
{$IFDEF DEBUG_SLT_SEW}
uses SLT.Common.Tracing;
{$ENDIF DEBUG_SLT_SEW}
const
PARAM_START_WITH_DATA = 'START_WITH_DATA'; // Do not localize
PARAM_START_WITH_DATA_CALLER = 'H'; // Do not localize
PARAM_START_WITH_DATA_TOKEN = 'T'; // Do not localize
{ TSLTShellExecuteWrapper }
//------------------------------------------------------------------------------
procedure TSLTShellExecuteWrapper.AllocData(var AData: Pointer; ADataSize: Integer);
begin
GetMem(AData, ADataSize);
end;
//------------------------------------------------------------------------------
destructor TSLTShellExecuteWrapper.Destroy();
begin
if FWindowHandle <> 0 then
begin
System.Classes.DeallocateHWnd(FWindowHandle);
FWindowHandle := 0;
end;
inherited Destroy();
end;
//------------------------------------------------------------------------------
class function TSLTShellExecuteWrapper.Execute(const AExeName: string; const AData: Pointer = nil; const ADataSize: DWORD = 0; AShowCmd: Integer = SW_SHOW): Boolean;
var
StartWithData: Boolean;
begin
Result := False;
with Self.Create() do
try
StartWithData := Assigned(AData) and (ADataSize > 0);
if Run(AExeName, StartWithData, AShowCmd) then
begin
if StartWithData then
Result := SendData(AData, ADataSize)
else
Result := True;
end
else
raise System.SysUtils.EOSError.Create(System.SysUtils.SysErrorMessage(Winapi.Windows.GetLastError()));
finally
Free();
end;
end;
//------------------------------------------------------------------------------
function TSLTShellExecuteWrapper.MakeExeName(const AExeName: string): string;
var
ModuleFileName: array[0..MAX_PATH-1] of Char;
begin
Result := AExeName;
// Si nom complet, exploite directement ce chemin
// Si juste nom du fichier, utilise le répertoire de l'appelant !
if ExtractFileDrive(AExeName) = '' then // gère <lecteur>:\<dossier>' aussi bien que '\\<serveur>\<nom_partagé>'.
begin
GetModuleFileName(0, ModuleFileName, MAX_PATH); // 0 c'est pour l'EXE même si depuis une DLL, avec HInstance cela fournirait le nom de la DLL
Result := ExtractFilePath(ModuleFileName) + ExtractFileName(AExeName);
end;
end;
//------------------------------------------------------------------------------
{$IFDEF DEBUG_SLT_SEW}
procedure TSLTShellExecuteWrapper.OutputDebugSEW(const Msg: string);
begin
TSLTDebugLogger.OutputDebugString('[SLT.SEW]', Msg);
end;
{$ENDIF DEBUG_SLT_SEW}
//------------------------------------------------------------------------------
function TSLTShellExecuteWrapper.MakeParams(AStartWithData: Boolean): string;
begin
if AStartWithData then
begin
FWindowHandle := AllocateHWnd(WndProc);
FCallerHandle := FWindowHandle;
System.SysUtils.CreateGUID(FToken);
Result := Format('/%s -%s0x%s -%s%s', [PARAM_START_WITH_DATA, PARAM_START_WITH_DATA_CALLER, IntToHex(FCallerHandle, SizeOf(FCallerHandle) * 2), PARAM_START_WITH_DATA_TOKEN, GUIDToString(FToken)]);
end
else
Result := '';
end;
//------------------------------------------------------------------------------
function TSLTShellExecuteWrapper.ReadData(out AData: Pointer; out ADataSize: DWORD): Boolean;
begin
Result := False;
// Attend que le programme appelant fournisse les données
if WaitResponse() then
begin
AData := FData;
ADataSize := FDataSize;
Result := True;
FData := nil;
FDataSize := 0;
end;
end;
//------------------------------------------------------------------------------
function TSLTShellExecuteWrapper.ReadParams(): Boolean;
var
HandleText, TokenText: string;
MsgDataHeader: TMsgHeader;
RawData: COPYDATASTRUCT;
begin
Result := False;
FReady := False;
if FindCmdLineSwitch(PARAM_START_WITH_DATA) then
begin
if FindCmdLineSwitch(PARAM_START_WITH_DATA_CALLER, HandleText, True, [clstValueAppended]) and TryStrToHWND(HandleText, FCallerHandle) and (FCallerHandle <> 0) then
begin
if FindCmdLineSwitch(PARAM_START_WITH_DATA_TOKEN, TokenText, True, [clstValueAppended]) then
begin
try
FToken := StringToGUID(TokenText);
FWindowHandle := System.Classes.AllocateHWnd(WndProc);
FReceiverHandle := FWindowHandle;
MsgDataHeader.Operation := mdoReceiverNeedData;
MsgDataHeader.Token := FToken;
MsgDataHeader.DataSize := 0;
RawData.dwData := 0;
RawData.cbData := SizeOf(MsgDataHeader);
RawData.lpData := @MsgDataHeader;
if SendMessage(FCallerHandle, WM_COPYDATA, FReceiverHandle, LPARAM(@RawData)) <> 0 then
Result := True;
except
on E: Exception do
begin
{$IFDEF DEBUG_SLT_SEW}
OutputDebugSEW(Format('Exception %s : "%s"', [E.ClassName(), E.Message]));
{$ENDIF DEBUG_SLT_SEW};
end;
end;
end;
end;
end;
end;
//------------------------------------------------------------------------------
class function TSLTShellExecuteWrapper.Receive(out AData: Pointer; out ADataSize: DWORD): Boolean;
begin
with Self.Create() do
try
Result := ReadParams() and ReadData(AData, ADataSize);
finally
Free();
end;
end;
//------------------------------------------------------------------------------
function TSLTShellExecuteWrapper.Run(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW): Boolean;
var
ShellFile: TFileName;
hProcessOfShell: HINST;
begin
ShellFile := MakeExeName(AExeName);
hProcessOfShell := ShellExecute(0, PChar('open'), PChar(ShellFile), PChar(MakeParams(AStartWithData)), PChar(ExtractFileDir(ShellFile)), AShowCmd);
// If the function ShellExecute fails, the return value is an error value that is less than or equal to 32.
// It can be cast only to an int and compared to either 32
Result := hProcessOfShell > 32;
end;
//------------------------------------------------------------------------------
function TSLTShellExecuteWrapper.SendData(const AData: Pointer; const ADataSize: DWORD): Boolean;
var
MsgDataHeader: TMsgHeader;
RawData: COPYDATASTRUCT;
Buf: Pointer;
BufCursor: PByte;
BufSize: DWORD;
begin
Result := False;
// Attend que le programme appelé réclame les données
if WaitResponse() then
begin
MsgDataHeader.Operation := mdoCallerSendData;
MsgDataHeader.Token := FToken;
MsgDataHeader.DataSize := ADataSize;
BufSize := SizeOf(MsgDataHeader) + ADataSize;
GetMem(Buf, BufSize);
try
BufCursor := Buf;
Move(MsgDataHeader, BufCursor^, SizeOf(MsgDataHeader));
Inc(BufCursor, SizeOf(MsgDataHeader));
Move(AData^, BufCursor^, ADataSize);
RawData.dwData := 0;
RawData.cbData := BufSize;
RawData.lpData := Buf;
if SendMessage(FReceiverHandle, WM_COPYDATA, FCallerHandle, LPARAM(@RawData)) <> 0 then
Result := True;
finally
FreeMem(Buf);
end;
end;
end;
//------------------------------------------------------------------------------
function TSLTShellExecuteWrapper.TryStrToHWND(const S: string; out Value: HWND): Boolean;
begin
// Il existe UIntToStr mais pas StrToUInt !!!
{$IFDEF CPUX86}
Result := TryStrToInt(S, Integer(Value))
{$ENDIF CPUX86}
{$IFDEF CPUX64}
Result := TryStrToInt64(S, Int64(Value));
{$ENDIF CPUX64}
end;
//------------------------------------------------------------------------------
function TSLTShellExecuteWrapper.WaitResponse(): Boolean;
var
SleepCount: Cardinal;
Msg: TMsg;
begin
SleepCount := 0;
// Attend que le programme appelant fournisse les identifiants
repeat
if SleepCount < 5000 then
begin
Sleep(1); // Environ 1.995 ms dont au plus 10s d'attente
Inc(SleepCount);
if PeekMessage(Msg, FWindowHandle, WM_COPYDATA, WM_COPYDATA, PM_REMOVE) then
begin
TranslateMessage(Msg);
DispatchMessage(Msg); // -> WndProc
end;
end
else
FAborted := True;
until FReady or FAborted;
Result := FReady;
end;
//------------------------------------------------------------------------------
procedure TSLTShellExecuteWrapper.WndProc(var Message: TMessage);
var
RawData: PCOPYDATASTRUCT;
MsgDataHeader: TMsgHeader;
BufCursor: PByte;
begin
if Message.Msg = WM_COPYDATA then
begin
RawData := PCOPYDATASTRUCT(Message.LParam);
if Assigned(RawData) then
begin
if RawData^.cbData >= SizeOf(TMsgHeader) then
begin
Move(RawData^.lpData^, MsgDataHeader, SizeOf(TMsgHeader));
case MsgDataHeader.Operation of
mdoReceiverNeedData :
begin
FReceiverHandle := HWND(Message.WParam);
FReady := (FReceiverHandle <> 0) and IsEqualGUID(FToken, MsgDataHeader.Token);
end;
mdoCallerSendData :
begin
if IsEqualGUID(FToken, MsgDataHeader.Token) and (FCallerHandle = HWND(Message.WParam)) then
begin
FReady := MsgDataHeader.DataSize > 0;
if FReady then
begin
BufCursor := RawData^.lpData;
Inc(BufCursor, SizeOf(MsgDataHeader));
AllocData(FData, MsgDataHeader.DataSize);
Move(BufCursor^, FData^, MsgDataHeader.DataSize);
FDataSize := MsgDataHeader.DataSize;
end
end;
end;
end;
if FReady then
begin
Message.Result := 1;
end
else
begin
Message.Result := 0;
FAborted := True;
end;
end;
end;
end
else
Message.Result := DefWindowProc(FWindowHandle, Message.Msg, Message.WParam, Message.LParam);
end;
{ TSLTProcessNotification }
//------------------------------------------------------------------------------
function TSLTProcessNotification.AddListener(AListener: TSLTProcessNotifyListener; AToken: TSLTProcessNotifyToken): Boolean;
var
TokenInfo: TTokenInfo;
begin
Result := False;
TokenInfo := FindToken(AToken);
if Assigned(TokenInfo) and not TokenInfo.Listeners.Contains(AListener) then
begin
TokenInfo.Listeners.Add(AListener);
Result := True;
end;
end;
//------------------------------------------------------------------------------
function TSLTProcessNotification.AddListenerByName(const AListenerName: string; AToken: TSLTProcessNotifyToken): Boolean;
var
ListenerHWND: HWND;
begin
ListenerHWND := FindWindow(nil, PChar(AListenerName));
if ListenerHWND <> 0 then
begin
Result := AddListener(ListenerHWND, AToken);
end
else
Result := False;
end;
//------------------------------------------------------------------------------
constructor TSLTProcessNotification.Create();
begin
inherited Create();
FTokens := TTokenList.Create(True);
FNotifications := TNotificationMap.Create();
end;
//------------------------------------------------------------------------------
destructor TSLTProcessNotification.Destroy();
begin
FreeAndNil(FNotifications);
FreeAndNil(FTokens);
if FListener <> 0 then
begin
System.Classes.DeallocateHWnd(FListener);
FListener := 0;
end;
inherited Destroy();
end;
//------------------------------------------------------------------------------
function TSLTProcessNotification.FindToken(AToken: TSLTProcessNotifyToken): TTokenInfo;
var
I: Integer;
begin
for I := 0 to FTokens.Count - 1 do
begin
Result := FTokens.Items[I];
if Result.Token = AToken then
Exit;
end;
Result := nil;
end;
//------------------------------------------------------------------------------
function TSLTProcessNotification.GetListener(): TSLTProcessNotifyListener;
begin
if FListener = 0 then
FListener := AllocateHWnd(WndProc);
Result := FListener;
end;
//------------------------------------------------------------------------------
function TSLTProcessNotification.GetListenerName(): string;
var
WindowText: array[0..MAX_PATH-1] of Char;
begin
if FListener <> 0 then
if GetWindowText(FListener, WindowText, MAX_PATH) > 0 then
FListenerName := WindowText;
Result := FListenerName;
end;
//------------------------------------------------------------------------------
function TSLTProcessNotification.Listen(): Boolean;
begin
Result := Listener <> 0;
if Result then
SetWindowText(FListener, PChar(FListenerName));
end;
//------------------------------------------------------------------------------
function TSLTProcessNotification.Notify(AListener: TSLTProcessNotifyListener; AToken: TSLTProcessNotifyToken): Boolean;
begin
Result := SendMessage(AListener, AToken, 0, 0) <> 0;
end;
//------------------------------------------------------------------------------
function TSLTProcessNotification.NotifyListeners(const ANotificationName: string): TSLTProcessNotifyToken;
begin
Result := RegisterNotification(ANotificationName);
NotifyListeners(Result);
end;
//------------------------------------------------------------------------------
procedure TSLTProcessNotification.NotifyListeners(AToken: TSLTProcessNotifyToken);
var
TokenInfo: TTokenInfo;
I: Integer;
begin
TokenInfo := FindToken(AToken);
if Assigned(TokenInfo) then
with TokenInfo.Listeners do
for I := 0 to Count - 1 do
Self.Notify(Items[I], AToken);
end;
//------------------------------------------------------------------------------
function TSLTProcessNotification.RegisterNotification(const ANotificationName: string): TSLTProcessNotifyToken;
begin
if not FNotifications.TryGetValue(ANotificationName, Result) then
begin
Result := RegisterWindowMessage(PChar(ANotificationName));
FNotifications.Add(ANotificationName, Result);
end;
if not Assigned(FindToken(Result)) then
FTokens.Add(TTokenInfo.Create(Result));
end;
//------------------------------------------------------------------------------
procedure TSLTProcessNotification.SetListenerName(const Value: string);
begin
FListenerName := Value;
if FListener <> 0 then
SetWindowText(FListener, PChar(FListenerName));
end;
//------------------------------------------------------------------------------
procedure TSLTProcessNotification.WndProc(var Message: TMessage);
begin
if not (Message.Msg in [WM_DESTROY, WM_NCDESTROY, WM_SETTEXT, WM_GETTEXT]) and Assigned(FTokens) and Assigned(FindToken(Message.Msg)) then
begin
if Assigned(FOnNotify) then
FOnNotify(Self, Message.Msg);
end
else
Message.Result := DefWindowProc(FListener, Message.Msg, Message.WParam, Message.LParam);
end;
{ TSLTProcessNotification.TTokenInfo }
//------------------------------------------------------------------------------
constructor TSLTProcessNotification.TTokenInfo.Create(AToken: TSLTProcessNotifyToken);
begin
inherited Create();
FToken := AToken;
FListeners := TListenerList.Create();
end;
//------------------------------------------------------------------------------
destructor TSLTProcessNotification.TTokenInfo.Destroy();
begin
FreeAndNil(FListeners);
inherited Destroy();
end;
{ TSLTCopyDataMessenger }
//------------------------------------------------------------------------------
procedure TSLTCopyDataMessenger.BeginWrite();
begin
CancelWrite();
end;
//------------------------------------------------------------------------------
procedure TSLTCopyDataMessenger.CancelWrite();
begin
FreeMem(FRawData.lpData);
ZeroMemory(@FRawData, SizeOf(FRawData));
end;
//------------------------------------------------------------------------------
destructor TSLTCopyDataMessenger.Destroy();
begin
CancelWrite();
if FListenerHandle <> 0 then
begin
DeallocateHWnd(FListenerHandle);
FListenerHandle := 0;
end;
inherited Destroy();
end;
//------------------------------------------------------------------------------
function TSLTCopyDataMessenger.DoDataAvailable(DataSender: HWND; Data: Pointer; DataLen: NativeUInt): Boolean;
begin
Result := False;
if Assigned(FOnDataAvailable) then
Result := FOnDataAvailable(Self, DataSender, Data, DataLen);
end;
//------------------------------------------------------------------------------
function TSLTCopyDataMessenger.EndWrite(): Boolean;
begin
// Le Handle d'écoute et de lecture est considéré comme le Handle émetteur (correspond à DataSender dans TSLTCopyDataMessengerReadEvent)
// Le Handle d'écriture, dans cette terminologie, est considéré comme le Handle récepteur (DataRecipient)
Result := SendMessage(FRecipientHandle, WM_COPYDATA, WPARAM(FListenerHandle), LPARAM(@FRawData)) <> 0;
CancelWrite();
end;
//------------------------------------------------------------------------------
function TSLTCopyDataMessenger.GetListenerHandle(): HWND;
begin
if FListenerHandle = 0 then
FListenerHandle := AllocateHWnd(WndProc);
Result := FListenerHandle;
end;
//------------------------------------------------------------------------------
function TSLTCopyDataMessenger.GetListenerName(): string;
var
WindowText: array[0..MAX_PATH-1] of Char;
begin
if FListenerHandle <> 0 then
if GetWindowText(FListenerHandle, WindowText, MAX_PATH) > 0 then
FListenerName := WindowText;
Result := FListenerName;
end;
//------------------------------------------------------------------------------
function TSLTCopyDataMessenger.GetRecipientName(): string;
var
WindowText: array[0..MAX_PATH-1] of Char;
begin
if FRecipientHandle <> 0 then
if GetWindowText(FRecipientHandle, WindowText, MAX_PATH) > 0 then
FRecipientName := WindowText;
Result := FRecipientName;
end;
//------------------------------------------------------------------------------
function TSLTCopyDataMessenger.Listen(): Boolean;
begin
Result := ListenerHandle <> 0;
if Result then
SetWindowText(FListenerHandle, PChar(FListenerName));
end;
//------------------------------------------------------------------------------
function TSLTCopyDataMessenger.ReadInteger(const Data: Pointer; out Value: Integer): Integer;
begin
Result := -1;
if not IsBadReadPtr(Data, SizeOf(Value)) then
begin
Value := PInteger(Data)^;
Result := SizeOf(Value);
end;
end;
//------------------------------------------------------------------------------
function TSLTCopyDataMessenger.ReadString(const Data: Pointer; out Value: string): Integer;
var
Len, IntSize, StrSize: Integer;
Cursor: PByte;
begin
Result := -1;
Len := 0;
IntSize := ReadInteger(Data, Len);
if IntSize > 0 then
begin
Result := IntSize;
if Len > 0 then
begin
Cursor := Data;
Inc(Cursor, IntSize);
SetLength(Value, Len);
StrSize := Len * SizeOf(Char); // gère que la table BMP de UTF-16
Move(Cursor^, Value[1], StrSize);
Inc(Result, StrSize);
end;
end;
end;
//------------------------------------------------------------------------------
function TSLTCopyDataMessenger.Seek(const Data: Pointer; Offset: NativeUInt): Pointer;
begin
Result := Pointer(NativeUInt(Data) + Offset);
end;
//------------------------------------------------------------------------------
procedure TSLTCopyDataMessenger.SetListenerName(const Value: string);
begin
// Change le nom pour le handle d'écoute
FListenerName := Value;
if FListenerHandle <> 0 then
SetWindowText(FListenerHandle, PChar(FListenerName));
end;
//------------------------------------------------------------------------------
procedure TSLTCopyDataMessenger.SetRecipientName(const Value: string);
begin
// Cherche par son nom le handle de destination
FRecipientName := Value;
FRecipientHandle := FindWindow(nil, PChar(FRecipientName))
end;
//------------------------------------------------------------------------------
procedure TSLTCopyDataMessenger.WndProc(var Message: TMessage);
var
PRawData: PCOPYDATASTRUCT;
begin
if Message.Msg = WM_COPYDATA then
begin
PRawData := PCOPYDATASTRUCT(Message.LParam);
Message.Result := 0;
if Assigned(PRawData) and (PRawData^.cbData > 0) then
if DoDataAvailable(HWND(Message.WParam), PRawData^.lpData, PRawData^.cbData) then
Message.Result := 1;
end
else
Message.Result := DefWindowProc(FListenerHandle, Message.Msg, Message.WParam, Message.LParam);
end;
//------------------------------------------------------------------------------
procedure TSLTCopyDataMessenger.WriteBuffer(const Data: Pointer; const DataLen: NativeUInt);
var
Position: Integer;
Cursor: PByte;
begin
Position := FRawData.cbData;
Inc(FRawData.cbData, DataLen);
if Position > 0 then
ReallocMem(FRawData.lpData, FRawData.cbData)
else
GetMem(FRawData.lpData, FRawData.cbData);
Cursor := FRawData.lpData;
Inc(Cursor, Position);
Move(Data^, Cursor^, DataLen);
end;
//------------------------------------------------------------------------------
procedure TSLTCopyDataMessenger.WriteInteger(const Value: Integer);
begin
WriteBuffer(@Value, SizeOf(Value));
end;
//------------------------------------------------------------------------------
procedure TSLTCopyDataMessenger.WriteString(const Value: string);
var
Len, Size: Integer;
begin
Len := Length(Value);
WriteInteger(Len);
if Len > 0 then
begin
Size := Len * SizeOf(Char); // gère que la table BMP de UTF-16
WriteBuffer(PChar(Value), Size);
end;
end;
{ TSLTShellLink }
//------------------------------------------------------------------------------
class function TSLTShellLink.ExtractTarget(const AShellLinkFileName: TFileName): TFileName;
// Voir la fonction cachée "GetFileNameFromLink" dans Vcl.ExtDlgs
// Ne pase inclure Winapi.Ole2 qui contient IID_IPersistFile, cela devient trop pénible les conflits entre TGUID de Delphi et TGUID de Winapi.Ole2
const
IID_IPersistFile: TGUID = '{0000010B-0000-0000-C000-000000000046}';
var
LResult: HRESULT;
LSHellLink: IShellLink;
LPersistFile: IPersistFile;
LFindData: TWin32FindData;
FileName: array[0..MAX_PATH - 1] of Char;
begin
Result := '';
LResult := CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IID_IShellLinkW, LShellLink);
if LResult = S_OK then
begin
if Supports(LShellLink, IID_IPersistFile, LPersistFile) then
begin
LResult := LPersistFile.Load(PChar(AShellLinkFileName), STGM_READ);
if LResult = S_OK then
begin
LResult := LSHellLink.GetPath(FileName, MAX_PATH, LFindData, SLGP_UNCPRIORITY);
if LResult = S_OK then
Result := Trim(FileName);
end;
end;
end;
end;
end. |
Partager