IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Delphi Discussion :

Lecture d'un fichier .LNK


Sujet :

Delphi

  1. #1
    Membre régulier

    Profil pro
    Inscrit en
    Avril 2004
    Messages
    536
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 536
    Points : 121
    Points
    121
    Par défaut Lecture d'un fichier .LNK
    Bonjour à tous

    J'ai besoin de savoir si un .LNK pointe vers un fichier ou un répertoire. Je veux donc vérifier ce point en lisant le nom du fichier ou répertoire pointé par le lien.

    Consulté (notamment) ces adresses :
    http://www.developpez.net/forums/d54...nk-raccourcis/

    http://www.developpez.net/forums/d34...contenu-d-lnk/

    J'ai retenu ce code :
    Ds les USUS : ShlObj, ActiveX, ComObj;

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    const
       TAILLE_BUFFER = 1024;
       IID_IPersistFile: TGUID = (D1: $0000010B; D2: $0000; D3: $0000; D4: ($C0, $00, $00, $00, $00, $00, $00, $46));
    
    type
       ArrayChar = array[0..TAILLE_BUFFER] of Char;
    
    Var  // globales
      // POUR LIRE LE F.LNK -------------------------
      PersistFile: IPersistFile;
      FileNameW: array[0..MAX_PATH] of WideChar;
      ShellLink: IShellLink;
      fd: TWin32FindData;
      ProLink: ArrayChar;
      I: Word;
      J: Integer;
      // --------------------------------------------
    
    
    
    procedure TForm1.Btn_LireClick(Sender: TObject);
    Var
      Nom_F_Lnk : String;
      Lst_Test_Fn : TStringList;
    
    begin
    
      Nom_F_LNK := 'GLOSSAIRES.lnk';  // Le fichier .LNK est ds le répertoire courant
      Form1.Lab_Aff_F_Lnk.Caption := UpperCase(Nom_F_LNK);
    
      Lst_Test_Fn := Lire_Infos_F_LNK(Nom_F_LNK);
      Lst_Test_Fn.SaveToFile('Z-RESULTAT.TMP');
    
    end;
    
    
    Function Lire_Infos_F_LNK(szChemin: String): TStringList;
    Var
      Nom_F_Lnk : string;
      Lst_Retour : TStringList;
    
    begin
    
          Lst_Retour := TStringList.Create;
          CoInitialize(nil);
          try
             OleCheck(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IID_IShellLinkA, ShellLink));
             try
                OleCheck(ShellLink.QueryInterface(IID_IPersistFile, PersistFile));
                try
                   MultiByteToWideChar(CP_ACP, 0, @szChemin[1], -1, FileNameW, MAX_PATH);
                   OleCheck(PersistFile.Load(FileNameW, STGM_READ));		// C'est là que ça plante
                   ShellLink.GetPath(ProLink, Max_Path, fd, SLGP_UNCPRIORITY);
                   Lst_Retour.Add(ProLink);
                finally
                end;
             finally
             end;
          finally
             CoUninitialize;
          end;
    end;
    Plantage avec le message (Erreur 2) "Fichier spécifié introuvable". Pourquoi ?

  2. #2
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 459
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 459
    Points : 24 873
    Points
    24 873
    Par défaut
    Mon code est très proche du tien sauf le transtypage en PChar bien plus simple en XE2

    Essaye mon code remplaçant IID_IShellLinkW par IID_IShellLinkA si tu es en D7

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    Winapi.Windows, Winapi.ShellApi, Winapi.ShlObj, Winapi.Messages, Winapi.ActiveX,
      System.Classes, System.SysUtils;
     
    type
      /// <summary>TSLTShellLink encapsule l'utilisation de l'interface IShellLink</summary>
      TSLTShellLink = class(TObject)
      public
        class function ExtractTarget(const AShellLinkFileName: TFileName): TFileName;
      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;
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  3. #3
    Membre régulier

    Profil pro
    Inscrit en
    Avril 2004
    Messages
    536
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 536
    Points : 121
    Points
    121
    Par défaut
    Bonjour, Shaire.

    XE7 . Mais je vais le tenter tout de même. Merci

  4. #4
    Expert éminent
    Avatar de Lung
    Profil pro
    Analyste-programmeur
    Inscrit en
    Mai 2002
    Messages
    2 664
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Analyste-programmeur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2002
    Messages : 2 664
    Points : 6 967
    Points
    6 967
    Par défaut
    J'ai testé sous XE7, et ça marche bien !

    L'urgent est fait, l'impossible est en cours, pour les miracles prévoir un délai. ___ Écrivez dans un français correct !!

    C++Builder 5 - Delphi 6#2 Entreprise - Delphi 2007 Entreprise - Delphi 2010 Architecte - Delphi XE Entreprise - Delphi XE7 Entreprise - Delphi 10 Entreprise - Delphi 10.3.2 Entreprise - Delphi 10.4.2 Entreprise - Delphi 11.1 Entreprise
    OpenGL 2.1 - Oracle 10g - Paradox - Interbase (XE) - PostgreSQL (15.4)

  5. #5
    Membre régulier

    Profil pro
    Inscrit en
    Avril 2004
    Messages
    536
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 536
    Points : 121
    Points
    121
    Par défaut
    Bonsoir à tous

    @Shaire : ça march nickel.

    Voici le code tel que je l'exploite :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
     
     
    Procedure Test_Fn_Shaire_Le_Troll;
    Var
      Nom_F_LNK : string;
      Nom_F_Pointe : string;
     
    begin
     
      Nom_F_LNK := 'Circoncision.lnk';
      Nom_F_pointe := TSLTShellLink.ExtractTarget(Nom_F_LNK);
      Form1.Lab_Aff_Retour_Fn_Shaire.Caption := Nom_F_Pointe;
     
      if Tst_F_Est_Un_Rep(Nom_F_pointe) = True then Form1.Lab_Aff_Si_Directory.Caption := 'OUI'  // Tst_F_Est_Un_Rep : fonction avec test des bits en ASM
      Else Form1.Lab_Aff_Si_Directory.Caption := 'NON';
     
    end;
    Merci

  6. #6
    Membre émérite

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2007
    Messages
    3 387
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2007
    Messages : 3 387
    Points : 2 999
    Points
    2 999
    Par défaut
    ça irait bien dans la faq ce bout de code ;-)

  7. #7
    Rédacteur/Modérateur

    Avatar de Roland Chastain
    Homme Profil pro
    Enseignant
    Inscrit en
    Décembre 2011
    Messages
    4 072
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Décembre 2011
    Messages : 4 072
    Points : 15 462
    Points
    15 462
    Billets dans le blog
    9
    Par défaut
    Citation Envoyé par Papy214 Voir le message
    ça irait bien dans la faq ce bout de code ;-)
    En effet.

    @ShaiLeTroll
    Est-ce que tu vois un inconvénient à ce que ton code soit ajouté tel quel dans la FAQ ?
    Mon site personnel consacré à MSEide+MSEgui : msegui.net

  8. #8
    Membre régulier

    Profil pro
    Inscrit en
    Avril 2004
    Messages
    536
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 536
    Points : 121
    Points
    121
    Par défaut
    Bonjour à tous

    Si cela peut intéresser quelqu'un, ci-joint un bout de code.
    Fichiers attachés Fichiers attachés

  9. #9
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 459
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 459
    Points : 24 873
    Points
    24 873
    Par défaut
    Citation Envoyé par Roland Chastain Voir le message
    @ShaiLeTroll
    Est-ce que tu vois un inconvénient à ce que ton code soit ajouté tel quel dans la FAQ ?
    Aucun problème !
    Tu peux l'ajouter tel quel dans la FAQ !

    Tout code que je fournis sur le forum est libre d'utilisation et je le partage avec plaisir !
    Voici l'unité complète concernant ShellApi et ShlObj qui regroupe un tas de code que j'ai pu améliorer grâce au forum.


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    973
    974
    975
    976
    977
    978
    979
    980
    981
    982
    983
    984
    985
    986
    987
    988
    989
    990
    991
    992
    993
    994
    995
    996
    997
    998
    999
    1000
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067
    1068
    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088
    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119
    1120
    1121
    1122
    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    1137
    1138
    1139
    1140
    1141
    1142
    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    1172
    1173
    1174
    1175
    1176
    1177
    1178
    1179
    1180
    1181
    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189
    1190
    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206
    1207
    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217
    1218
    1219
    1220
    1221
    1222
    1223
    1224
    1225
    1226
    1227
    1228
    1229
    1230
    1231
    1232
    1233
    1234
    1235
    1236
    1237
    1238
    1239
    1240
    1241
    1242
    1243
    1244
    1245
    1246
    1247
    1248
    1249
    1250
    1251
    1252
    1253
    1254
    1255
    1256
    1257
    1258
    1259
    1260
    1261
    1262
    1263
    1264
    1265
    1266
    1267
    1268
    1269
    1270
    1271
    1272
    1273
    1274
     
    //------------------------------------------------------------------------------
    (*                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"
     *                                                                             -
     *  Version alternative publiée sur "www.developpez.net"                       -
     *  Post : "Redirection des entrées/sorties du process (ping)"                 -
     *  Post Number : 3793892                                                      -
     *  Post URL = "http://www.developpez.net/forums/d453153-2/environnements-developpement/delphi/langage/redirection-entrees-sorties-process-ping/#post3793892"
     *                                                                             -
     *  Copyright "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                                                                 -
     *                                                                             -
     * 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>TSLTShellExecuteWrapperCallCmdEvent est un évènement lié à la méthode CallCmd qui se produit lorsque des données sont renvoyés par le canaux sortie et erreur par le programme console lancé</summary>
      /// <param name="Output">Chaine du canal de sortie</param>
      /// <param name="Error">Chaine du canal d'erreur</param>
      /// <param name="AbortProcess">Indique si l'on souhaite arreté le programme console</param>
      TSLTShellExecuteWrapperCallCmdEvent = procedure(const Output, Error: string; var AbortProcess: Boolean) of object;
     
      /// <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&lt;2009&gt;</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; const AExtraParam: string = ''): Boolean;
        function RunByCreateProcess(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
        function RunByShellExecute(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
        function MakeExeName(const AExeName: string): string;
        function MakeParams(AStartWithData: Boolean; const AExtraParam: string = ''): 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}
      public
        // Types Publiques
        type
          TProcessIdList = System.Generics.Collections.TList<DWORD>;
      private
        // Membres Privés de classe
        class var FProcessIdList: TProcessIdList;
        // Accesseurs de classe
        class function GetProcessIdList(): TProcessIdList; static;
      protected
        // Méthodes Protégées
        procedure AllocData(var AData: Pointer; ADataSize: Integer); virtual;
      public
        // Constructeurs Publiques
        destructor Destroy(); override;
        class destructor Destroy();
     
        // Méthodes Publiques
        class function Execute(const AExeName: string; const AData: Pointer = nil; const ADataSize: DWORD = 0; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
        class function Receive(out AData: Pointer; out ADataSize: DWORD): Boolean;
        class function CallCmd(const CmdDirectory, CmdName, CmdParam: string; out ExitCode: Int64; out OutputText: string; out ErrorText: string; Delay: Cardinal = INFINITE; WaitEvent: TSLTShellExecuteWrapperCallCmdEvent = nil; PipeMaxSize: Cardinal = 0): Boolean;
     
        // Propriétés Publiques
        class property ProcessIdList: TProcessIdList read GetProcessIdList;
      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 NotifyByName(const AListenerName: string; 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;
     
    {* -----------------------------------------------------------------------------
    la fonction CallCmd permet de lancer un programme console, tout en récupérant en quasi temps-réel le contenu devant normalement s'y afficher
    @param CmdDirectory Dossier contenant le Fichier CmdName
    @param CmdName programme console à executer
    @param CmdParam paramètres de la ligne de commande
    @param ExitCode Code de Sortie renvoyé par le programme console, -1 si non récupéré
    @param OutputText chaine contenant tout ce qui aurait du s'afficher (canal sortie)
    @param ErrorText chaine contenant tout ce qui a été signalé comme erreurs (canal erreur)
    @param Delay indique le temps entre chaque cycle de lecture des canaux, détermine la fréquence de lancement de WaitEvent, par défaut, cela attend que le programme console se termine
    @param WaitEvent procédure à lancer lorsque le Delay est écoulé, Output et Error contiennent les derniers éléments envoyés par le programme console sur les canaux depuis le dernier délai, AbortProcess indique si la processus doit être arrêté
    @param PipeMaxSize défini la taille maximal que l'on lit à chaque chaque cycle de lecture des canaux, si zéro, taille non limitée par défaut
    @return Indique si le programme a été lancé
    ------------------------------------------------------------------------------ }
    class function TSLTShellExecuteWrapper.CallCmd(const CmdDirectory, CmdName, CmdParam: string; out ExitCode: Int64; out OutputText: string; out ErrorText: string; Delay: Cardinal = INFINITE; WaitEvent: TSLTShellExecuteWrapperCallCmdEvent = nil; PipeMaxSize: Cardinal = 0): Boolean;
    var
      StartupInfo: TStartupInfo;
      ProcessInfo: TProcessInformation;
      CmdLine: string; // utile pour le débogage
      SecurityAttr : TSecurityAttributes;
      hReadPipeInput, hWritePipeInput: NativeUInt;
      hReadPipeOutput, hWritePipeOutput: NativeUInt;
      hReadPipeError, hWritePipeError: NativeUInt;
      lpCurrentDirectory: PChar;
      Terminated: Boolean;
      AbortProcess: Boolean;
      HandleFunctionProcess: Cardinal;
     
      function ReadPipe(Handle: Cardinal; out Buf: string): Boolean;
      const
        MAX_INT: Cardinal = MaxInt;
      var
        PipeSize: Cardinal;
        PipeToRead, PipeReaded: Cardinal;
        PipeBuf: array of AnsiChar;
        AnsiBuf: AnsiString;
      begin
        PipeSize := GetFileSize(Handle, nil); // On oublie si cela dépasse 2Go ... normalement c'est 4Ko
        if (PipeMaxSize > 0) and (PipeSize > PipeMaxSize) then
          PipeToRead := PipeMaxSize
        else
          PipeToRead := PipeSize;
     
        Result := PipeToRead > 0;
        if Result then
        begin
          SetLength(PipeBuf, PipeToRead);
          ZeroMemory(@PipeBuf[0], PipeToRead);
          ReadFile(Handle, PipeBuf[0], PipeToRead, PipeReaded, nil);
     
          SetLength(AnsiBuf, PipeToRead);
          OemToAnsi(@PipeBuf[0], @AnsiBuf[1]);
          Buf := string(AnsiBuf);
        end;
      end;
     
      procedure ReadPipes();
      var
        DeltaOutputText: string;
        DeltaErrorText: string;
      begin
        if ReadPipe(hReadPipeOutput, DeltaOutputText) then
          OutputText := OutputText + DeltaOutputText;
        if ReadPipe(hReadPipeError, DeltaErrorText) then
          ErrorText := ErrorText + DeltaErrorText;
        try
          if Assigned(WaitEvent) then
            WaitEvent(DeltaOutputText, DeltaErrorText, AbortProcess);
        except
          on E: Exception do
            OutputDebugString(PChar(Format('s.CallCmd.ReadPipes.WaitEvent - "%s" : "%s"', [Self.ClassName(), E.ClassName(), E.Message])));
        end;
      end;
     
    begin
      (*
      Result := True;
      OutputText := 'Dummy Output';
      ErrorText := 'Dummy Error';
      ErrorCode := 0;
      Exit;
      *)
      OutputText := '';
      ErrorText := '';
      try
        SecurityAttr.nLength := SizeOf(TSecurityAttributes);
        SecurityAttr.lpSecurityDescriptor := nil;
        SecurityAttr.bInheritHandle := True;
        if CreatePipe(hReadPipeInput, hWritePipeInput, @SecurityAttr, 0) and
          CreatePipe(hReadPipeOutput, hWritePipeOutput, @SecurityAttr, 0) and
          CreatePipe(hReadPipeError, hWritePipeError, @SecurityAttr, 0) then
        begin
          try
            ZeroMemory(@StartupInfo, SizeOf(StartupInfo)); // GetStartupInfo(StartupInfo);
            StartupInfo.cb := SizeOf(StartupInfo);
            StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; // Active wShowWindow et hStdOutput/hStdError
            StartupInfo.wShowWindow := SW_HIDE;
            StartupInfo.hStdInput := hReadPipeInput;
            StartupInfo.hStdOutput := hWritePipeOutput;
            StartupInfo.hStdError := hWritePipeError;
            ZeroMemory(@ProcessInfo, SizeOf(ProcessInfo));
     
            if CmdDirectory <> '' then
            begin
              CmdLine := Format('"%s%s" %s', [IncludeTrailingPathDelimiter(CmdDirectory), CmdName, CmdParam]);
              lpCurrentDirectory := PChar(CmdDirectory);
            end
            else
            begin
              CmdLine := Format('%s %s', [CmdName, CmdParam]);
              lpCurrentDirectory := nil;
            end;
     
            Result := CreateProcess(nil, PChar(CmdLine), @SecurityAttr, @SecurityAttr, True, 0, nil, lpCurrentDirectory, StartupInfo, ProcessInfo);
            if Result then
            begin
              try
                Terminated := False;
                AbortProcess := False;
                while not Terminated do
                begin
                  case WaitForSingleObject(ProcessInfo.hProcess, Delay) of
                    WAIT_OBJECT_0 :
                      begin
                        ReadPipes();
                        Terminated := True;
                      end;
                    WAIT_ABANDONED : Terminated := True;
                    WAIT_TIMEOUT :
                      begin
                        ReadPipes();
                        Terminated := Delay = INFINITE;
                      end;
                    WAIT_FAILED: Abort;
                  else
                    Terminated := True;
                  end;
     
                  if AbortProcess then
                  begin
                   HandleFunctionProcess := OpenProcess(PROCESS_TERMINATE, False, ProcessInfo.dwProcessId);
                   if HandleFunctionProcess > 0 then
                   begin
                     TerminateProcess(HandleFunctionProcess, 0);
                     CloseHandle(HandleFunctionProcess);
                   end;
                  end;
                end;
     
                TULargeInteger(ExitCode).HighPart := 0;
                if not GetExitCodeProcess(ProcessInfo.hProcess, TULargeInteger(ExitCode).LowPart) then
                  ExitCode := -1;
              finally
                CloseHandle(ProcessInfo.hThread);
                CloseHandle(ProcessInfo.hProcess); // The handles for both the process and the main thread must be closed through calls to CloseHandle
              end;
            end;
          finally
            CloseHandle(hReadPipeInput);
            CloseHandle(hWritePipeInput);
            CloseHandle(hReadPipeOutput);
            CloseHandle(hWritePipeOutput);
            CloseHandle(hReadPipeError);
            CloseHandle(hWritePipeError);
          end;
        end
        else
          raise Exception.Create('Impossible de créer les Pipes');
      except
        on E: Exception do
        begin
          OutputDebugString(PChar(Format('%s.CallCmd Error %s, Message : %s', [Self.ClassName(), E.ClassName(), E.Message])));
          raise;
        end;
      end;
    end;
     
     
    //------------------------------------------------------------------------------
    class destructor TSLTShellExecuteWrapper.Destroy();
    begin
      FreeAndNil(FProcessIdList);
    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; const AExtraParam: string = ''): Boolean;
    var
      StartWithData: Boolean;
    begin
      Result := False;
     
      with Self.Create() do
      try
        StartWithData := Assigned(AData) and (ADataSize > 0);
        if Run(AExeName, StartWithData, AShowCmd, AExtraParam) 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;
     
    //------------------------------------------------------------------------------
    class function TSLTShellExecuteWrapper.GetProcessIdList(): TProcessIdList;
    begin
      if not Assigned(FProcessIdList) then
        FProcessIdList := TProcessIdList.Create();
     
      Result := FProcessIdList;
    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; const AExtraParam: string = ''): 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)]);
        if AExtraParam <> '' then
          Result := AExtraParam + ' ' + Result;
      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; const AExtraParam: string = ''): Boolean;
    begin
      // This system metric is used in a Terminal Services environment.
      // If the calling process is associated with a Terminal Services client session, the return value is nonzero.
      // If the calling process is associated with the Terminal Server console session, the return value is 0.
      // CreateProcess permet d'éviter un avertissement lié à l'emplacement du fichier
      // Sur un serveur via Terminal Server, l'emplacement devrait être toujours exprimé sous la forme d'un chemin réseau UNC
      // Sur un poste utilisateur, mieux vaut se limiter à un accès local même si rien n'empêche d'accéder par réseau à une ressource externe
      if LongBool(GetSystemMetrics(SM_REMOTESESSION)) then
        Result := RunByCreateProcess(AExeName, AStartWithData, AShowCmd, AExtraParam)
      else
        Result := RunByShellExecute(AExeName, AStartWithData, AShowCmd, AExtraParam);
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.RunByCreateProcess(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
    var
      StartupInfo: TStartupInfo;
      ProcessInfo: TProcessInformation;
      SecurityAttr : TSecurityAttributes;
      ProcessFile: TFileName;
      CmdLine, CmdParam, CmdDirectory: string;
    begin
      try
        SecurityAttr.nLength := SizeOf(TSecurityAttributes);
        SecurityAttr.lpSecurityDescriptor := nil;
        SecurityAttr.bInheritHandle := True;
     
        ZeroMemory(@StartupInfo, SizeOf(StartupInfo)); // GetStartupInfo(StartupInfo);
        StartupInfo.cb := SizeOf(StartupInfo);
        StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
        StartupInfo.wShowWindow := AShowCmd;
        ProcessFile := MakeExeName(AExeName);
        CmdParam := MakeParams(AStartWithData, AExtraParam);
        CmdLine := Format('"%s" %s', [AExeName, CmdParam]);
        CmdDirectory := ExtractFileDir(AExeName);
        Result := CreateProcess(nil, PChar(CmdLine), @SecurityAttr, @SecurityAttr, True, 0, nil, PChar(CmdDirectory), StartupInfo, ProcessInfo);
        if Result then
        begin
          // Mémorise tous les processus lancés par TSLTShellExecuteWrapper
          ProcessIdList.Add(ProcessInfo.dwProcessId);
          // Je ne dois pas conserver le process ouvert, cela ne ferme que les pointeurs sur le process mais celui reste bien actif
          // MSDN : "Handles in PROCESS_INFORMATION must be closed with CloseHandle when they are no longer needed."
          // Ne pas confondre CloseHandle et TerminateProcess !
          // En Citrix, cela semble conserver le fichier vérouillé (en local,
          CloseHandle(ProcessInfo.hThread);
          CloseHandle(ProcessInfo.hProcess); // The handles for both the process and the main thread must be closed through calls to CloseHandle
        end;
      except
        on E: Exception do
        begin
          OutputDebugString(PChar(Format('TSLTShellExecuteWrapper.RunByCreateProcess Error %s, Message : %s', [E.ClassName, E.Message])));
          raise;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TSLTShellExecuteWrapper.RunByShellExecute(const AExeName: string; AStartWithData: Boolean; AShowCmd: Integer = SW_SHOW; const AExtraParam: string = ''): Boolean;
    var
      ShellFile: TFileName;
      ExecuteInfo: TShellExecuteInfo;
    begin
      ShellFile := MakeExeName(AExeName);
      with ExecuteInfo do
      begin
        cbSize := Sizeof(ExecuteInfo);
        fMask := SEE_MASK_NOCLOSEPROCESS;
        Wnd := 0;
        lpVerb := PChar('open');
        lpFile := PChar(ShellFile);
        lpParameters := PChar(MakeParams(AStartWithData, AExtraParam));
        lpDirectory := PChar(ExtractFileDir(ShellFile));
        nShow := AShowCmd;
      end;
     
      Result := ShellExecuteEx(@ExecuteInfo);
      if Result and (ExecuteInfo.hProcess > 0) then
      begin
        // Mémorise tous les processus lancés par TSLTShellExecuteWrapper
        ProcessIdList.Add(GetProcessId(ExecuteInfo.hProcess));
        // Nettoyage !
        CloseHandle(ExecuteInfo.hProcess); // The calling application is responsible for closing the handle when it is no longer needed.
      end;
    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.NotifyByName(const AListenerName: string; AToken: TSLTProcessNotifyToken): Boolean;
    begin
      Result := AddListenerByName(AListenerName, AToken);
      NotifyListeners(AToken);
    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.
    [HS]
    @bvsud
    Mon pseudo c'est Shaï Le Troll, j'évite le ï dans un login, cela ne passe par partout
    cela vient de Shaï Hulud de Dune quoi qu'elle aurait pur être musicale !

    D'où te vient ce "Shaire" est un mélange de Shaï et Share ...
    [/HS]
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  10. #10
    Membre régulier

    Profil pro
    Inscrit en
    Avril 2004
    Messages
    536
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 536
    Points : 121
    Points
    121
    Par défaut
    @ShaiLeTroll : pardon ! J'avais mal lu! J'ai effectivement pensé à Share

  11. #11
    Membre chevronné

    Profil pro
    Inscrit en
    Août 2005
    Messages
    1 011
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2005
    Messages : 1 011
    Points : 2 078
    Points
    2 078
    Par défaut Lnk
    Bonjour,
    Je ne sais pas trop quel code sera mis dans la FAQ mais peut être que dans la période actuelle il vaudrait mieux éviter
    Nom_F_LNK := 'Circoncision.lnk';
    Peut-etre
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Nom_F_LNK := 'Developpez.lnk';
    serait moins connoté

  12. #12
    Rédacteur/Modérateur

    Avatar de Roland Chastain
    Homme Profil pro
    Enseignant
    Inscrit en
    Décembre 2011
    Messages
    4 072
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Décembre 2011
    Messages : 4 072
    Points : 15 462
    Points
    15 462
    Billets dans le blog
    9
    Par défaut
    Voilà, c'est fait :

    http://delphi.developpez.com/faq/?pa...ci-de-type-LNK

    Curieusement, je ne suis pas arrivé à utiliser la fonction dans une application console. Pourquoi ?

    @ShaiLeTroll
    Merci pour ton unité.
    Mon site personnel consacré à MSEide+MSEgui : msegui.net

  13. #13
    Membre régulier

    Profil pro
    Inscrit en
    Avril 2004
    Messages
    536
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 536
    Points : 121
    Points
    121
    Par défaut
    @Gaby277 : mdr ! Oui, en effet. C'est un lien que j'ai créé sur un fichier, au hasard, ds ma base d'articles.

  14. #14
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 459
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 459
    Points : 24 873
    Points
    24 873
    Par défaut
    Citation Envoyé par Roland Chastain Voir le message
    Curieusement, je ne suis pas arrivé à utiliser la fonction dans une application console. Pourquoi ?
    Je n'utilise jamais d'application console mais je pense qu'il manque le CoInitialize dans ce cas
    il était naturellement effectué par l'objet VCL TApplication en D7 avec un appel explicite de CoInitialize
    En XE2, c'est indirect, l'inclusion de System.Win.ComObj (inclu par le méandre de la VCL) modifie System.InitProc, TApplication.Initialize appel InitProc qui appèle CoInitialize


    Idem, dans un TThread, sans CoInitialize dans le Execute, l'appel ne fonctionnerait pas


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    program ZooShaiConsoleLNK;
     
    {$APPTYPE CONSOLE}
     
    {$R *.res}
     
    uses
      System.SysUtils,
      SLT.Common.Winapi.ShellApi, Winapi.ActiveX;
     
    begin
      try
        Winapi.ActiveX.CoInitialize(nil);
        Writeln(TSLTShellLink.ExtractTarget('C:\Users\xxx\Desktop\Delphi XE2.lnk'));
        Readln;
      except
        on E: Exception do
          Writeln(E.ClassName, ': ', E.Message);
      end;
    end.
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  15. #15
    Rédacteur/Modérateur

    Avatar de Roland Chastain
    Homme Profil pro
    Enseignant
    Inscrit en
    Décembre 2011
    Messages
    4 072
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Décembre 2011
    Messages : 4 072
    Points : 15 462
    Points
    15 462
    Billets dans le blog
    9
    Par défaut
    Citation Envoyé par ShaiLeTroll Voir le message
    Je n'utilise jamais d'application console mais je pense qu'il manque le CoInitialize dans ce cas
    Merci pour l'explication et le code.
    Mon site personnel consacré à MSEide+MSEgui : msegui.net

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [Windows]lecture des fichier lnk (raccourcis)
    Par Tiaps dans le forum API standards et tierces
    Réponses: 10
    Dernier message: 21/10/2009, 19h27
  2. Réponses: 6
    Dernier message: 02/09/2003, 15h12
  3. Lecture et ecriture fichier .ini
    Par despe dans le forum C
    Réponses: 6
    Dernier message: 23/07/2003, 20h40
  4. [langage] Optimiser la lecture d'un fichier
    Par And_the_problem_is dans le forum Langage
    Réponses: 4
    Dernier message: 05/02/2003, 08h54
  5. [langage] Optimiser la lecture d'un fichier
    Par And_the_problem_is dans le forum Langage
    Réponses: 2
    Dernier message: 11/06/2002, 10h24

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo