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

Langage Delphi Discussion :

WM_COPYDATA jamais reçu


Sujet :

Langage Delphi

  1. #1
    Membre régulier
    Profil pro
    Inscrit en
    Mars 2006
    Messages
    147
    Détails du profil
    Informations personnelles :
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Mars 2006
    Messages : 147
    Points : 84
    Points
    84
    Par défaut WM_COPYDATA jamais reçu
    Bonjour,

    J'ai suivi ce tuto pour utiliser WM_COPYDATA : http://alphomega.developpez.com/EchangeVal/
    Pas moyen que ça fonctionne. C'est sans doute évident mais je ne vois pas pourquoi....

    Deux process, PRG et SVC tournent.
    Ils utilisent tous deux cette classe TMesTest.

    PRG fait les Sendmessage.
    SVC est censé les recevoir.

    SVC reçoit bien WM_TEST mais jamais WM_COPYDATA.

    J'ai le nez dedans depuis des jours et je n'y vois plus rien.
    En fait ça a même fonctionné à un moment : WM_COPYDATA bien reçu, mais impossible de récupérer les données...

    Pour le moment si je pouvais déjà recevoir le message ....

    Faut-il une procédure particulière pour recevoir WM_COPYDATA ?


    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
     
    unit mestest;
     
    interface
     
    uses
    classes
    ,mniconst
    ,windows
    ,messages
    ,SysUtils
    ;
     
    type
     
     TCopyDataStruct = record
      dwData: LongInt;
      cbData: LongInt;
      lpData: Pointer;
     end;
     PCopyDataStruct = ^TCopyDataStruct;
     
     TCopyData = packed record
      Str: string;
      TypeStr : TWMCopyDataStr;
     end;
     PCopyData = ^TCopyData;
     
    TMesTest =  class(TThread)
      private
        WHO_AM_I : TBbProc;
        FWinHandle: HWND;
        WM_TEST: Cardinal;
        WinProc : TWinProc;
        Procedure trace(pi_str: string);
        function SendString(StrType, Str: String; Dest : TbbProc) : Boolean;
      protected
        procedure Execute; override;
        procedure WndProc(var msg: TMessage);
      public
        Constructor Create(Proc : TBbProc;O:pointer);
        destructor Destroy; override;
    end;
     
    implementation
    uses
    DateUtils
    ,mnishare
    ,StrUtils
    ;
     
    var
      CopyDataStruct: TCopyDataStruct;
         CopyData : TCopyData;
     
    procedure TMesTest.Execute;
    var dbg : String;
      i : integer;
      Msg : TMsg;
      win : THandle;
    begin
      while NOT Terminated do begin
        if WHO_AM_I = Prg then begin
           win := FindWindow(PChar(WinProc[TBbProc.SVC]),nil);
           if win > 0 then begin
             trace('Envoi de WM_TEST' + IntToStr(win) + ' ' + WinProc[TBbProc.SVC]);
             SendMessageTimeout(win, WM_TEST, 0, 0, SMTO_BLOCK, 500, nil);
             sleep(1000);
             trace('Envoi de WM_COPYDATA' + IntToStr(win) + ' ' + WinProc[TBbProc.SVC]);
             SendString('Type','Str',TBbProc.SVC);
           end;
        end;
        Sleep(1000);
      end;
    end;
     
    function TMesTest.SendString(StrType: String; Str: string; Dest: TBbProc):Boolean;
    var  Win : THandle;
    begin
     trace('SendString COPYDATA : ' + 'Dest=' + WinProc[Dest] + ', Type=' + StrType + ', Str='+Str);
     result := false;
     Str := UpperCase(StrType) + ':' + Str;
     win := FindWindow(PChar(WinProc[Dest]),nil);
     
     if win > 0 then begin
        CopyData.Str := Str;
        CopyData.TypeStr := TWMCopyDataStr.RUN;
        CopyDataStruct.dwData := 1;
        CopyDataStruct.cbData := SizeOf(CopyData);
        CopyDataStruct.lpData := @CopyData;
        SendMessage(Win, WM_COPYDATA, 0, LongInt(@CopyDataStruct));
     end;
    end;
     
    procedure TMesTest.WndProc(var msg: TMessage);
    var Str : String;
        StrType : TWMCopyDataStr;
    begin
      trace('WndProc : entrée (réception d''un message) ');
      if (Msg.Msg = WM_COPYDATA)  then begin // ICI : On ne reçoit JAMAIS le message
        trace('WndProc : Réception de WM_COPYDATA'); // Jamais exécuté
      end;
      if (Msg.Msg = WM_TEST) then begin // ICI : ça fonctionne
        trace('WndProc : Réception de WM_TEST');  // Ok
      end;
    end;
     
     
    Constructor TMesTest.Create(Proc: TBbProc;o:Pointer);
    var dbg : String;
      i: Integer;
    begin
      WHO_AM_I := Proc;
      WM_TEST := RegisterWindowMessage(PChar('WM_TEST'));
      WinProc[PRG] := 'WM_TEST'+prgprocess;
      WinProc[SVC] := 'WM_TEST'+svcprocess;
      FWinHandle := DSiAllocateHWnd(WinProc[WHO_AM_I],WndProc,WS_EX_NOACTIVATE,0);
      inherited Create(False);
    end;
     
    destructor TMesTest.Destroy;
    begin
      DSiDeallocateHWnd(WinProc[WHO_AM_I], FWinHandle);
      inherited;
    end;
     
    end.
    André.

  2. #2
    Rédacteur/Modérateur
    Avatar de Andnotor
    Inscrit en
    Septembre 2008
    Messages
    5 694
    Détails du profil
    Informations personnelles :
    Localisation : Autre

    Informations forums :
    Inscription : Septembre 2008
    Messages : 5 694
    Points : 13 130
    Points
    13 130
    Par défaut
    Citation Envoyé par sinfoni Voir le message
    En fait ça a même fonctionné à un moment : WM_COPYDATA bien reçu, mais impossible de récupérer les données...
    Le record TCopyData ne peut pas contenir de pointeur et string n'est qu'un pointeur
    Au plus simple, c'est une chaîne de taille fixe string[255] ou un tableau de caractères array[0..255] of char.

  3. #3
    Membre régulier
    Profil pro
    Inscrit en
    Mars 2006
    Messages
    147
    Détails du profil
    Informations personnelles :
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Mars 2006
    Messages : 147
    Points : 84
    Points
    84
    Par défaut
    J'ai donc mis un string[255]. J'ai repris la structure du tutao "EnvoiFax"... Ca ne va pas mieux. Je reçois WM_TEST, pas WM_COPYDATA.
    (J'ai aussi corrigé la partie Thread en créant la windows dans le Execute.)

    Et est-ce à dire qu'il est impossible de passer une chaine de plus de 255 caractères ???

    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
     
    unit mestest;
     
    interface
     
    uses
    classes
    ,mniconst
    ,windows
    ,messages
    ,SysUtils
    ;
     
    type
     
     
     PCopyDataStruct = ^TCopyDataStruct;
     TCopyDataStruct = record
      dwData: LongInt;
      cbData: LongInt;
      lpData: Pointer;
     end;
     
    type
     PEnvoiFax = ^TEnvoiFax;
     TEnvoiFax = packed record
      Destinataire: string[255];
      TypeDocument: integer;
      DateEnvoi: TDateTime;
      EnvoiFait: boolean;
     end;
     
    etc...
    EDIT : J'ai résolu mon cas en utilisant WM_SETTEXT à la place de WM_COPYDATA puisque la finalité est de passer une chaîne de caractères. Toutefois le non fonctionnement du WM_COPYDATA m'échappe.

  4. #4
    Rédacteur/Modérateur
    Avatar de Andnotor
    Inscrit en
    Septembre 2008
    Messages
    5 694
    Détails du profil
    Informations personnelles :
    Localisation : Autre

    Informations forums :
    Inscription : Septembre 2008
    Messages : 5 694
    Points : 13 130
    Points
    13 130
    Par défaut
    Il n'y a rien qui me choque particulièrement dans ce code mais quelques interrogations tout de même :
    • Es-tu sûr d'envoyer WM_COPYDATA ? Le premier FindWindow est fait sur un TBbProc.SVC alors que le deuxième simplement sur un TBbProc. TBbProc.SVC est de type TBbProc ? Pas clair
    • Pourquoi ne pas passer win à SendString puisque tu as déjà récupéré le handle de la cible ?
    • Qu'est-ce que SendMessage retourne ? Que renvoie GetLastError ?


    Citation Envoyé par sinfoni Voir le message
    Et est-ce à dire qu'il est impossible de passer une chaine de plus de 255 caractères ???
    Si en passant par GetMem/FreeMem ou bien sûr un array of char de la taille (max) souhaitée.

  5. #5
    Membre expérimenté Avatar de guillemouze
    Profil pro
    Inscrit en
    Novembre 2004
    Messages
    876
    Détails du profil
    Informations personnelles :
    Âge : 41
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations forums :
    Inscription : Novembre 2004
    Messages : 876
    Points : 1 448
    Points
    1 448
    Par défaut
    Pour etre vraiement sûr, j'enverrai un WM_TEST juste avant le copydata, pour bien verifier que ton message est envoyé au même handle:
    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
    function TMesTest.SendString(StrType: String; Str: string; Dest: TBbProc):Boolean;
    var  Win : THandle;
    begin
     trace('SendString COPYDATA : ' + 'Dest=' + WinProc[Dest] + ', Type=' + StrType + ', Str='+Str);
     result := false;
     Str := UpperCase(StrType) + ':' + Str;
     win := FindWindow(PChar(WinProc[Dest]),nil);
     
     if win > 0 then begin
        CopyData.Str := Str;
        CopyData.TypeStr := TWMCopyDataStr.RUN;
        CopyDataStruct.dwData := 1;
        CopyDataStruct.cbData := SizeOf(CopyData);
        CopyDataStruct.lpData := @CopyData;
        SendMessage(Win, WM_TEST, 0, 1); //1 pour le différencier de l'autre sendMessage WM_TEST
        SendMessage(Win, WM_COPYDATA, 0, LongInt(@CopyDataStruct));
     end;
    end;

  6. #6
    Membre régulier
    Profil pro
    Inscrit en
    Mars 2006
    Messages
    147
    Détails du profil
    Informations personnelles :
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Mars 2006
    Messages : 147
    Points : 84
    Points
    84
    Par défaut
    Citation Envoyé par Andnotor Voir le message
    Es-tu sûr d'envoyer WM_COPYDATA ?
    Oui, le SendString qui fait le SendMessage est dans le code joint... Il est fait juste après le WM_TEST:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    SendMessage(Win, WM_COPYDATA, 0, LongInt(@CopyDataStruct));
    Citation Envoyé par Andnotor Voir le message
    Le premier FindWindow est fait sur un TBbProc.SVC alors que le deuxième simplement sur un TBbProc. TBbProc.SVC est de type TBbProc ? Pas clair
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    TBbProc = (SVC,PRG,DLL,STP,MAJ,TST);
    C'est une liste de processus : Programme, service, mise à jour etc. qui utilisent tous la même classe TMes pour communiquer.
    Quand on crée une instance de TMes, on passe en paramètre TbbProc.SVC, TbbProc.PRG etc.
    Chaque thread TMes sait donc simplement pour quel processus il travaille.
    A chaque valeur possible de Tbbproc est associée une constante String.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    TWinProc = array [low(TBbProc)..high(TBbPRoc)] of String;
    Quabd j'appelle mon AllocateHWnd, je passe cette constante qui est utilisée comme classe. Pour chaque processus, on a donc une window ayant une classe différente. Ce qui permet à mes FindWindow de trouver le bon thread dans le bon processus.

    Citation Envoyé par Andnotor Voir le message
    [*]Pourquoi ne pas passer win à SendString puisque tu as déjà récupéré le handle de la cible ?
    Ca c'est juste parce que le SendString de la classe d'origine n'est normalement pas appelé ici.
    J'ai créé la classe TMesTest en enlevant le maximum de code afin d'isolé le problème.

    Citation Envoyé par Andnotor Voir le message
    [*]Qu'est-ce que SendMessage retourne ?
    Il retourne 0

    Citation Envoyé par Andnotor Voir le message
    Que renvoie GetLastError ?
    Je n'ai pas testé et j'ai modifié le code depuis pour passer par WM_SETTEXT au lieu de WM_COPYDATA.
    Je retesterai dès que possible... mais j'ai perdu tellement de temps avec ce WM_COPYDATA que je n'ai plus de temps à passer sur ce problème cette semaine

  7. #7
    Expert éminent sénior
    Avatar de Paul TOTH
    Homme Profil pro
    Freelance
    Inscrit en
    Novembre 2002
    Messages
    8 964
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

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

    Informations forums :
    Inscription : Novembre 2002
    Messages : 8 964
    Points : 28 445
    Points
    28 445
    Par défaut
    d'après Microsoft wParam devrait contenir le Handle de la fenêtre émettrice.
    Developpez.com: Mes articles, forum FlashPascal
    Entreprise: Execute SARL
    Le Store Excute Store

  8. #8
    Membre régulier
    Profil pro
    Inscrit en
    Mars 2006
    Messages
    147
    Détails du profil
    Informations personnelles :
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Mars 2006
    Messages : 147
    Points : 84
    Points
    84
    Par défaut
    Citation Envoyé par guillemouze Voir le message
    Pour etre vraiement sûr, j'enverrai un WM_TEST juste avant le copydata, pour bien verifier que ton message est envoyé au même handle:
    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
    function TMesTest.SendString(StrType: String; Str: string; Dest: TBbProc):Boolean;
    var  Win : THandle;
    begin
     trace('SendString COPYDATA : ' + 'Dest=' + WinProc[Dest] + ', Type=' + StrType + ', Str='+Str);
     result := false;
     Str := UpperCase(StrType) + ':' + Str;
     win := FindWindow(PChar(WinProc[Dest]),nil);
     
     if win > 0 then begin
        CopyData.Str := Str;
        CopyData.TypeStr := TWMCopyDataStr.RUN;
        CopyDataStruct.dwData := 1;
        CopyDataStruct.cbData := SizeOf(CopyData);
        CopyDataStruct.lpData := @CopyData;
        SendMessage(Win, WM_TEST, 0, 1); //1 pour le différencier de l'autre sendMessage WM_TEST
        SendMessage(Win, WM_COPYDATA, 0, LongInt(@CopyDataStruct));
     end;
    end;
    WM_TEST bien reçu...

  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
    Je me suis fait une classe pour encapsuler ce besoin d'échange : TSLTCopyDataMessenger

    Comme toi, j'ai abandonné depuis longtemps l'utilisation d'une fenêtre de Delphi au profit d'une fenêtre neutre purement Windows !
    Bien plus fiable pour gérer le nom de classe, le findwindow ...
    Mais JAMAIS dans un Thread !

    Et je confirme, qu'il faut mettre le FCallerHandle comme le mentionne Paul Toth


    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
     
    //------------------------------------------------------------------------------
    (*                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&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): 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.
    avec un code exemple d'exploitation

    l'idée est d'appeler un programme de lui passer un numéro de chose et cela lance une fenetre pour l'afficher
    Puis lorsque le programme tourne déjà cela lui passe le numéro et cela affiche aussi la fenêtre


    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
     
      TxxxModuleCensureMachinTruc = class(TObject)
      public
        type
          TMachinTrucNotifyEvent = procedure(ANumeroMachinTruc: Integer) of object;
          TStartDataHeader = packed record
            Cmd: Integer;
          end;
          TStartWithMachinTruc = packed record
            Header: TStartDataHeader;
            MachinTruc: Integer;
          end;
        const
          WND_NAME = 'xxx.CensureMachinTruc.Messenger';
          CMD_NOTIFY_MachinTruc = 1;
      private
        class var
          FModuleFileName: TFileName;
          FModuleMessenger: TxxxCopyDataMessenger;
          FOnMachinTruc: TMachinTrucNotifyEvent;
      private
        class function GetModuleMessenger(): TxxxCopyDataMessenger; static;
        class procedure SetOnMachinTruc(const Value: TMachinTrucNotifyEvent); static;
      private
        class function ShowMachinTrucInCurrentInstance(ANumeroMachinTruc: Integer): Boolean;
        class function ShowMachinTrucInNewInstance(ANumeroMachinTruc: Integer): Boolean;
        class function ModuleMessengerDataAvailableEventHandler(Sender: TObject; DataSender: HWND; Data: Pointer; DataLen: NativeUInt): Boolean;
        class function HandleMachinTruc(Data: Pointer): Boolean;
        class procedure DoMachinTruc(ANumeroMachinTruc: Integer);
      private
        class property ModuleMessenger: TxxxCopyDataMessenger read GetModuleMessenger;
      public
        class function ShowMachinTruc(ANumeroMachinTruc: Integer): Boolean;
        class function StartWithMachinTruc(out MachinTruc: Integer): Boolean;
     
        class property ModuleFileName: TFileName read FModuleFileName write FModuleFileName;
        class property OnMachinTruc: TMachinTrucNotifyEvent read FOnMachinTruc write SetOnMachinTruc;
      public
        // Constructeurs de Classe
        class destructor Destroy();
      end;
     
      { TxxxModuleCensureMachinTruc }
     
    //------------------------------------------------------------------------------
    class destructor TxxxModuleCensureMachinTruc.Destroy();
    begin
      FreeAndNil(FModuleMessenger);
    end;
     
    //------------------------------------------------------------------------------
    class procedure TxxxModuleCensureMachinTruc.DoMachinTruc(ANumeroMachinTruc: Integer);
    begin
      if Assigned(FOnMachinTruc) then
        FOnMachinTruc(ANumeroMachinTruc);
    end;
     
    //------------------------------------------------------------------------------
    class function TxxxModuleCensureMachinTruc.GetModuleMessenger(): TxxxCopyDataMessenger;
    begin
      if not Assigned(FModuleMessenger) then
        FModuleMessenger := TxxxCopyDataMessenger.Create();
     
      Result := FModuleMessenger;
    end;
     
    //------------------------------------------------------------------------------
    class function TxxxModuleCensureMachinTruc.HandleMachinTruc(Data: Pointer): Boolean;
    var
      MachinTruc: Integer;
    begin
      Result := False;
     
      if ModuleMessenger.ReadInteger(Data, MachinTruc) > 0 then
      begin
        DoMachinTruc(MachinTruc);
        Result := True;
      end;
    end;
     
    //------------------------------------------------------------------------------
    class function TxxxModuleCensureMachinTruc.ModuleMessengerDataAvailableEventHandler(Sender: TObject; DataSender: HWND; Data: Pointer; DataLen: NativeUInt): Boolean;
    var
      Cmd: Integer;
      AmtTransferred: Integer;
    begin
      Result := False;
      if Sender = ModuleMessenger then
      begin
        AmtTransferred := ModuleMessenger.ReadInteger(Data, Cmd);
        if AmtTransferred > 0 then
        begin
          case Cmd of
            CMD_NOTIFY_MachinTruc : Result := HandleMachinTruc(ModuleMessenger.Seek(Data, AmtTransferred));
          end;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    class procedure TxxxModuleCensureMachinTruc.SetOnMachinTruc(const Value: TMachinTrucNotifyEvent);
    begin
      FOnMachinTruc := Value;
      ModuleMessenger.ListenerName := WND_NAME;
      if ModuleMessenger.Listen() then
        ModuleMessenger.OnDataAvailable := ModuleMessengerDataAvailableEventHandler;
    end;
     
    //------------------------------------------------------------------------------
    class function TxxxModuleCensureMachinTruc.ShowMachinTruc(ANumeroMachinTruc: Integer): Boolean;
    begin
      if ShowMachinTrucInCurrentInstance(ANumeroMachinTruc) then
        Result := True
      else
        Result := ShowMachinTrucInNewInstance(ANumeroMachinTruc);
    end;
     
    //------------------------------------------------------------------------------
    class function TxxxModuleCensureMachinTruc.ShowMachinTrucInCurrentInstance(ANumeroMachinTruc: Integer): Boolean;
    begin
      ModuleMessenger.RecipientName := WND_NAME;
      if ModuleMessenger.RecipientHandle <> 0 then
      begin
        ModuleMessenger.BeginWrite();
        ModuleMessenger.WriteInteger(CMD_NOTIFY_MachinTruc);
        ModuleMessenger.WriteInteger(ANumeroMachinTruc);
        Result := ModuleMessenger.EndWrite();
      end
      else
        Result := False;
    end;
     
    //------------------------------------------------------------------------------
    class function TxxxModuleCensureMachinTruc.ShowMachinTrucInNewInstance(ANumeroMachinTruc: Integer): Boolean;
    var
      PromptValue, PromptExt: string;
      Param: TStartWithMachinTruc;
    begin
      Result := False;
     
      if FModuleFileName = '' then
      begin
        PromptValue := '';
        // Avec un Filter 'Censure MachinTruc|*.EXE|Raccourci|*.LNK', cela résoud le LNK automatiquement
        // Avec un Filter 'Module|CensureMachinTruc.EXE|Raccourci|*.LNK', cela NE résoud PAS le LNK !!!
        if PromptForFileName(PromptValue, 'Censure MachinTruc|*.EXE|Raccourci|*.LNK', '.EXE', 'Où est installé le module "Censure MachinTruc" connu sous le nom de "Poisson Jaune" ?', PromptValue) then
        begin
          PromptExt := ExtractFileExt(PromptValue);
          if SameText(PromptExt, '.EXE') then
            FModuleFileName := PromptValue
          else if SameText(PromptExt, '.LNK') then
            FModuleFileName := TSLTShellLink.ExtractTarget(PromptValue)
          else
           Exit;
        end
        else
          Exit;
      end;
     
      Param.Header.Cmd := CMD_NOTIFY_MachinTruc;
      Param.MachinTruc := ANumeroMachinTruc;
      Result := TxxxModuleTool.ShellExecute(FModuleFileName, SW_SHOW, @Param, SizeOf(Param));
    end;
     
    //------------------------------------------------------------------------------
    class function TxxxModuleCensureMachinTruc.StartWithMachinTruc(out MachinTruc: Integer): Boolean;
    var
      Data: Pointer;
      DataSize: DWORD;
    begin
      MachinTruc := -1;
      if TSLTShellExecuteWrapper.Receive(Data, DataSize) then
        if DataSize = SizeOf(TStartWithMachinTruc) then
          if TStartWithMachinTruc(Data^).Header.Cmd = CMD_NOTIFY_MachinTruc then
            MachinTruc := TStartWithMachinTruc(Data^).MachinTruc;
     
      Result := MachinTruc > 0;
    end;
    Dans le programme appelé :

    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
    procedure TfmTrucBidule.FormCreate(Sender: TObject);
    begin
      TxxxModuleCensureMachinTruc.OnMachinTruc := InteropMachinTrucNotifyEventHandler;
     
    end;
     
    procedure TfmHistoMachinTruc.InteropMachinTrucNotifyEventHandler(ANumeroMachinTruc: Integer);
    begin
      // SLT 2014-05-27 : Interconnexion entre les modules
      ShowMachinTruc(ANumeroMachinTruc);
    end;
     
    procedure TfmTrucBidule.ShowMachinTruc(ANumeroMachinTruc: Integer);
    begin
      if ANumeroMachinTruc > 0 then
      begin
        // SLT 2014-05-27 : Interconnexion entre les modules
        edtNoObjet.Text := Format('%.9d', [ANumeroMachinTruc]);
        Application.BringToFront();
        BtnValider.Click();
      end;
    end;
    Dans le programme appelant :
    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
     
    //------------------------------------------------------------------------------
    procedure TModuleAppelantForm.AfficheMachinTruc(AMachinTrucNumero: Integer);
    var
      Patience: TObject;
    begin
      Patience := TxxxPatience.Create();
      try
        TxxxPatience.Show(Patience);
        TxxxModuleCensureMachinTruc.ModuleFileName := TModuleAppelant.Instance.ConfigLocal.ModuleFileNameMachinTruc;
        TxxxModuleCensureMachinTruc.ShowMachinTruc(AMachinTrucNumero);
        TxxxPatience.Hide(Patience);
      finally
        Patience.Free();
      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

  10. #10
    Rédacteur/Modérateur
    Avatar de Andnotor
    Inscrit en
    Septembre 2008
    Messages
    5 694
    Détails du profil
    Informations personnelles :
    Localisation : Autre

    Informations forums :
    Inscription : Septembre 2008
    Messages : 5 694
    Points : 13 130
    Points
    13 130
    Par défaut
    Non, wParam peut très bien être à 0 et créer une fenêtre dans un thread n'est pas un problème non plus. Par contre, il ne faut pas passer par AllocateHWND qui n'est pas thread-safe mais par CreateWindow.

    Sinfoni utilise dsiAllocateHWND qui permet semble-t-il d'utiliser une méthode en lieu et place d'une simple procédure (le genre de bidouille que je n'apprécie guère) mais son appel est mal placé (il devrait être dans Execute), cette fenêtre est créée dans le thread principal (pas le but recherché).

    @Sinfoni
    Petite question simple, est-ce que tu compiles en 32 ou 64 bits ?

  11. #11
    Membre régulier
    Profil pro
    Inscrit en
    Mars 2006
    Messages
    147
    Détails du profil
    Informations personnelles :
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Mars 2006
    Messages : 147
    Points : 84
    Points
    84
    Par défaut
    Citation Envoyé par Andnotor Voir le message
    Non, wParam peut très bien être à 0 et créer une fenêtre dans un thread n'est pas un problème non plus. Par contre, il ne faut pas passer par AllocateHWND qui n'est pas thread-safe mais par CreateWindow.
    Absolument, j'utilise bien un createWindow, et non le AllocateHWND.

    Citation Envoyé par Andnotor Voir le message
    Sinfoni utilise dsiAllocateHWND qui permet semble-t-il d'utiliser une méthode en lieu et place d'une simple procédure (le genre de bidouille que je n'apprécie guère) mais son appel est mal placé (il devrait être dans Execute), cette fenêtre est créée dans le thread principal (pas le but recherché).
    Oui, mal placé dans le premier exemple de code fourni. J'ai indiqué dans mon deuxième Post que j'ai corrigé cette erreur
    J'ai aussi corrigé la partie Thread en créant la windows dans le Execute.

    Citation Envoyé par Andnotor Voir le message
    Petite question simple, est-ce que tu compiles en 32 ou 64 bits ?
    Les deux. Les tests que j'ai effectués ont été fait en 64 bits.

    Je vais essayer de faire le test en passant le Handle de l'appelant pour en avoir le coeur net.

  12. #12
    Rédacteur/Modérateur
    Avatar de Andnotor
    Inscrit en
    Septembre 2008
    Messages
    5 694
    Détails du profil
    Informations personnelles :
    Localisation : Autre

    Informations forums :
    Inscription : Septembre 2008
    Messages : 5 694
    Points : 13 130
    Points
    13 130
    Par défaut
    Citation Envoyé par sinfoni Voir le message
    Les tests que j'ai effectués ont été fait en 64 bits.
    Alors ton appel est incorrect, le paramètre lParam n'est pas un LongInt (32 bits). Transtype en LPARAM. LPARAM (NativeInt) sera 32 ou 64 bits en fonction de la plateforme cible.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    SendMessage(Win, WM_COPYDATA, 0, LPARAM(@CopyDataStruct));

  13. #13
    Membre régulier
    Profil pro
    Inscrit en
    Mars 2006
    Messages
    147
    Détails du profil
    Informations personnelles :
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Mars 2006
    Messages : 147
    Points : 84
    Points
    84
    Par défaut
    Citation Envoyé par Andnotor Voir le message
    Alors ton appel est incorrect, le paramètre lParam n'est pas un LongInt (32 bits). Transtype en LPARAM. LPARAM (NativeInt) sera 32 ou 64 bits en fonction de la plateforme cible.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    SendMessage(Win, WM_COPYDATA, 0, LPARAM(@CopyDataStruct));
    Absolument, très bien vu.
    Message bien reçu quand le programme est compilé en 32.

    Merci !

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

Discussions similaires

  1. login with ajax mail de confirmation jamais reçu
    Par kevin254kl dans le forum WordPress
    Réponses: 4
    Dernier message: 03/05/2015, 15h22
  2. [OL-2007] "Envoyer vers destinataire" jamais reçu
    Par Danielclaude93 dans le forum Outlook
    Réponses: 0
    Dernier message: 05/03/2013, 12h38
  3. [Messages Windows] WM_QUIT jamais reçu?
    Par shifty.net dans le forum Windows
    Réponses: 5
    Dernier message: 15/07/2006, 18h52
  4. [servlet]problème de variable jamais nulle
    Par omega dans le forum Servlets/JSP
    Réponses: 2
    Dernier message: 18/03/2004, 09h31
  5. Ne jamais mettre le focus sur un tbutton, possible
    Par portu dans le forum Composants VCL
    Réponses: 4
    Dernier message: 03/07/2003, 15h06

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