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 :

UnmapViewOfFile "Exception"


Sujet :

Langage Delphi

  1. #1
    Membre éprouvé Avatar de BuzzLeclaire
    Homme Profil pro
    Dev/For/Vte/Ass
    Inscrit en
    Août 2008
    Messages
    1 606
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Dev/For/Vte/Ass

    Informations forums :
    Inscription : Août 2008
    Messages : 1 606
    Points : 1 113
    Points
    1 113
    Par défaut UnmapViewOfFile "Exception"
    Bonsoir à tous,

    Je m'amuse à utiliser File Mapping de la sorte :

    Démarrage

    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
    Function TFMyForm.Demarrage: Boolean;
    begin
      Result := False;
      Try
        FichierEchange:=CreateFileMapping( $FFFFFFFF,  
                                  nil,               
                                  PAGE_READWRITE, 
                                  0,
                                  SizeOf(Partage),
                                  'ApplicationCible');
     
        if FichierEchange = 0 then Exit(False);
     
        Partage := MapViewOfFile(FichierEchange, 
                            FILE_MAP_WRITE,
                            0,
                            0,
                            0);
     
        if Partage = nil then Exit(False);
     
    //...
     
        Result := True;
      Except
        Result := False;
      end;
    Arrêt

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    Function TFMyForm.Arret: Boolean;
    begin
      if Partage <> nil then
      begin
        UnmapViewOfFile(Partage);
        if FichierEchange <> 0 then
        begin
          CloseHandle(FichierEchange);
        end;
      end;
    end;
    Lorsque j'utilise fonction démarrage cela fonctionne très, mais lorsque j'ai fini et que j'utilise la fonction arrêt, j'ai systématiquement cette erreur

    Violation d'accès à l'adresse 007E8D23 dans le module...

    Je suis sur XE5.

    Auriez-vous une idée à ce problème ?

    Merci.

  2. #2
    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
    salut,

    à part une petite erreur de logique, la raison de l'erreur ne me saute pas aux yeux

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    Function TFMyForm.Arret: Boolean;
    begin
      if FichierEchange <> 0 then
      begin
        if Partage <> nil then
          UnmapViewOfFile(Partage);
        CloseHandle(FichierEchange);
      end;
    end;
    d'après ton code démarrage, tu peux avoir ouvert le fichier avec un Partage à nil
    Developpez.com: Mes articles, forum FlashPascal
    Entreprise: Execute SARL
    Le Store Excute Store

  3. #3
    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
    j'ajouterais aussi un reset de Partage et FichierEchange après libération si Arret est appelé deux fois par erreur
    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

  4. #4
    Membre éprouvé Avatar de BuzzLeclaire
    Homme Profil pro
    Dev/For/Vte/Ass
    Inscrit en
    Août 2008
    Messages
    1 606
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Dev/For/Vte/Ass

    Informations forums :
    Inscription : Août 2008
    Messages : 1 606
    Points : 1 113
    Points
    1 113
    Par défaut
    Bonjour Paul et Shail,

    @Paul OK Merci, j'ai vu les deux versions sur le net ce que tu évoques et aussi ce genre :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    procedure TForm1.FormDestroy(Sender: TObject);
    begin
       AdoConnection1.Connected := False;
     
      if assigned(SharedData) then
        UnmapViewOfFile(SharedData);
      if hFileMapping > 0 then
        CloseHandle(hFileMapping);
    end;
    @Shail, normalement impossible, mais tu peux m'expliquer ?

    De toute façon l'erreur n'est pas sur le CloseHandel !!! désolé je me suis trompé c'est sur UnmapViewOfFile(Partage); (je ne sais pas si je peut changer le titre de la discussion ?)

    J'ai tenté de faire ceci mais cela ne change rien !!

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    Function TFMyForm.Arret: Boolean;
    begin
      if FichierEchange <> 0 then
      begin
        if Partage <> nil then UnmapViewOfFile(Partage);
     
        CloseHandle(FichierEchange);
      end;
    End;
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
        Partage := MapViewOfFile(FichierEchange, 
                            FILE_MAP_ALL_ACCESS,    
                            0,                
                            0,                
                            0);

    Pour information, Ouverture

    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
        FichierEchange := OpenFileMapping(FILE_MAP_WRITE,False,'ApplicationCible');
        if FichierEchange <> 0 then
        begin
          Partage := PPartage(MapViewOfFile(FichierEchange,FILE_MAP_WRITE,0,0,0));
          if Partage <> nil then
          begin
            Souris := Pointer(Donnees);
     
            Partage^.Fenetre    := Souris^.hwnd;
            Partage^.SourisPosx := Souris^.Pt.x;
            Partage^.SourisPosy := Souris^.Pt.y;
     
            PostMessage(Partage^.HandleApplicationCible, WM_USER+0913, MsgID, Donnees);
     
            UnmapViewOfFile(Partage);
          end;
          CloseHandle(FichierEchange);
        end;

    Une autre idée ?

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

    Informations forums :
    Inscription : Septembre 2008
    Messages : 5 693
    Points : 13 128
    Points
    13 128
    Par défaut
    UnmapViewOfFile ne va pas générer de VA, juste retourner FALSE en cas d'erreur.

    Mais une chose est sûr tu écris au-delà du fichier, le fichier mappé ne faisant que 4 octets (SizeOf(Partage) = taille d'un pointeur).

  6. #6
    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
    Les violations d'accès c'est parfois retord et pas là où l'on croit, on écrit là il ne fallait pas, on écrase la mauvaise valeur et paf le programme s'affole


    Sinon, pourquoi si compliqué ? un bon vieux WM_COPYDATA suffira largement pour échanger de la données entre deux programme si tu en es l'auteur, voir mon code TSLTCopyDataMessenger

    Note que SendMessage est bloquant et PostMessage est asynchrone
    En fait, pourquoi envoyer Donnees par PostMessage alors que vous avez Partage ?
    L'idée du partage c'est justement d'écrire dans le partage, protéger éventuellement par une section critique (Mutex), et via Sémaphore avertir le destinataire qu'une donnée est disponible, le fichier de partage étant défini à la taille de la donnée

    voir plus bas mon code, j'avais fait un délire entre un EXE, un ActiveX et un Script PHP, ce dernier invoquait l'ActiveX pour appeler des fonctions métier de l'EXE, j'avais prévu pour échange asynchrone avec des données de longueurs variables (ex WideString en D7)

    voir aussi les ATOM dans ce tutoriel


    Le fameux délire, en fait reprise d'un protocol TCP/IP de 2003 que j'ai repris pour la structure du partage en 2010, le script PHP pouvait facilement invoquer une méthode par seconde donc ça débitait pas mal dans le fichier de partage
    En parallèle, l'EXE lui lisait les Pipes du process PHP.exe pour récupérer un log

    Regarde SendPacket() et les fonctions WaitSend [Check Lock], BeginSend [Alloc Partage], Send [Ecriture Partage], EndSend [Unalloc Partage, UnLock, Semaphore]
    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
    1275
    1276
    1277
    1278
    1279
    1280
    1281
    1282
    1283
    1284
    1285
    1286
    1287
    1288
    1289
    1290
    1291
    1292
    1293
    1294
    1295
    1296
    1297
    1298
    1299
    1300
    1301
    1302
    1303
    1304
    1305
    1306
    1307
    1308
    1309
    1310
    1311
    1312
    1313
    1314
    1315
    1316
    1317
    1318
    1319
    1320
    1321
    1322
    1323
    1324
    1325
    1326
    1327
    1328
    1329
    1330
    1331
    1332
    1333
    1334
    1335
    1336
    1337
    1338
    1339
    1340
    1341
    1342
    1343
    1344
    1345
    1346
    1347
    1348
    1349
    1350
    1351
    1352
    1353
    1354
    1355
    1356
    1357
    1358
    1359
    1360
    1361
    1362
    1363
    1364
    1365
    1366
    1367
    1368
    1369
    1370
    1371
    1372
    1373
    1374
    1375
    1376
    1377
    1378
    1379
    1380
    1381
    1382
    1383
    1384
    1385
    1386
    1387
    1388
    1389
    1390
    1391
    1392
    1393
    1394
    1395
    1396
    1397
    1398
    1399
    1400
    1401
    1402
    1403
    1404
    1405
    1406
    1407
    1408
    1409
    1410
    1411
    1412
    1413
    1414
    1415
    1416
    1417
    1418
    1419
    1420
    1421
    1422
    1423
    1424
    1425
    1426
    1427
    1428
    1429
    1430
    1431
    1432
    1433
    1434
    1435
    1436
    1437
    1438
    1439
    1440
    1441
    1442
    1443
    1444
    1445
    1446
    1447
    1448
    1449
    1450
    1451
    1452
    1453
    1454
    1455
    1456
    1457
    1458
    1459
    1460
    1461
    1462
    1463
    1464
    1465
    1466
    1467
    1468
    1469
    1470
    1471
    1472
    1473
    1474
    1475
    1476
    1477
    1478
    1479
    1480
    1481
    1482
    1483
    1484
    1485
    1486
    1487
    1488
    1489
    1490
    1491
    1492
    1493
    1494
    1495
    1496
    1497
    1498
    1499
    1500
    1501
    1502
    1503
    1504
    1505
    1506
    1507
    1508
    1509
    1510
    1511
    1512
    1513
    1514
    1515
    1516
    1517
    1518
    1519
    1520
    1521
    1522
    1523
    1524
    1525
    1526
    1527
    1528
    1529
    1530
    1531
    1532
    1533
    1534
    1535
    1536
    1537
    1538
    1539
    1540
    1541
    1542
    1543
    1544
    1545
    1546
    1547
    1548
    1549
    1550
    1551
    1552
    1553
    1554
    1555
    1556
    1557
    1558
    1559
    1560
    1561
    1562
    1563
    1564
    1565
    1566
    1567
    1568
    1569
    1570
    1571
    1572
    1573
    1574
    1575
    1576
    1577
    1578
    1579
    1580
    1581
    1582
    1583
    1584
    1585
    1586
    1587
    1588
    1589
    1590
    1591
    1592
    1593
    1594
    1595
    1596
    1597
    1598
    1599
    1600
    1601
    1602
    1603
    1604
    1605
    1606
    1607
    1608
    1609
    1610
    1611
    1612
    1613
    1614
    1615
    1616
    1617
    1618
    1619
    1620
    1621
    1622
    1623
    1624
    1625
    1626
    1627
    1628
    1629
    1630
    1631
    1632
    1633
    1634
    1635
    1636
    1637
    1638
    1639
    1640
    1641
    1642
    1643
    1644
    1645
    1646
    1647
    1648
    1649
    1650
    1651
    1652
    1653
    1654
    1655
    1656
    1657
    1658
    1659
    1660
    1661
    1662
    1663
    1664
    1665
    1666
    1667
    1668
    1669
    1670
    1671
    1672
    1673
    1674
    1675
    1676
    1677
    1678
    1679
    1680
    1681
    1682
    1683
    1684
    1685
    1686
    1687
    1688
    1689
    1690
    1691
    1692
    1693
    1694
    1695
    1696
    1697
    1698
    1699
    1700
    1701
    1702
    1703
    1704
    1705
    1706
    1707
    1708
    1709
    1710
    1711
    1712
    1713
    1714
    1715
    1716
    1717
    1718
    1719
    1720
    1721
    1722
    1723
    1724
    1725
    1726
    1727
    1728
    1729
    1730
    1731
    1732
    1733
    1734
    1735
    1736
    1737
    1738
    1739
    1740
    1741
    1742
    1743
    1744
    1745
    1746
    1747
    1748
    1749
    1750
    1751
    1752
    1753
    1754
    1755
    1756
    1757
    1758
    1759
    1760
    1761
    1762
    1763
    1764
    1765
    1766
    1767
    1768
    1769
    1770
    1771
    1772
    1773
    1774
    1775
    1776
    1777
    1778
    1779
    1780
    1781
    1782
    1783
    1784
    1785
    1786
    1787
    1788
    1789
    1790
    1791
    1792
    1793
    1794
    1795
    1796
    1797
    1798
    1799
    1800
    1801
    1802
    1803
    1804
    1805
    1806
    1807
    1808
    1809
    1810
    1811
    1812
    1813
    1814
    1815
    1816
    1817
    1818
    1819
    1820
    1821
    1822
    1823
    1824
    1825
    1826
    1827
    1828
    1829
    1830
    1831
    1832
    1833
    1834
    1835
    1836
    1837
    1838
    1839
    1840
    1841
    1842
    1843
    1844
    1845
    1846
    1847
    1848
    1849
    1850
    1851
    1852
    1853
    1854
    1855
    1856
    1857
    1858
    1859
    1860
    1861
    1862
    1863
    1864
    1865
    1866
    1867
    1868
    1869
    1870
    1871
    1872
    1873
    1874
    1875
    1876
    1877
    1878
    1879
    1880
    1881
    1882
    1883
    1884
    1885
    1886
    1887
    1888
    1889
    1890
    1891
    1892
    1893
    1894
    1895
    1896
    1897
    1898
    1899
    1900
    1901
    1902
    1903
    1904
    1905
    1906
    1907
    1908
    1909
    1910
    1911
    1912
    1913
    1914
    1915
    1916
    1917
    1918
    1919
    1920
    1921
    1922
    1923
    1924
    unit ShaiTrollInterOp_Classes;
     
    {$WARN SYMBOL_PLATFORM OFF}
     
    interface
     
    uses Windows, SysUtils, Classes, ComObj, Math, StrUtils, IniFiles,    dialogs,
      ShaiTrollInterOpCOM_TLB;
     
    // http://msdn.microsoft.com/en-us/library/aa366537(VS.85).aspx
    // http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx
     
    type
      EShaiTrollInterOpCommunicationInterCOMInstanceError = class(EOleSysError)
      public
        constructor Create(const Msg: string; ErrorCode: HRESULT = E_UNEXPECTED);
        constructor CreateFmt(const Msg: string; const Args: array of const; ErrorCode: HRESULT = E_UNEXPECTED);
      end;
     
      TShaiTrollInterOpCommunicationInterCOMInstanceEventLogType = (ltNone, ltException, ltError, ltWarning, ltInfo);
     
      TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer = class;
      TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient = class;
      TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList = class;
      TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener = class;
      TShaiTrollInterOpCommunicationInterCOMInstancePacketList = class;
      TShaiTrollInterOpCommunicationInterCOMInstanceDispatcher = class;
      TShaiTrollInterOpCommunicationInterCOMInstanceSender = class;
     
      TShaiTrollInterOpCommunicationInterCOMInstanceManager = class
      private
        FEvents: IShaiTrollInterOpEvents;
        FIniFile: TIniFile;
        FModeServer: Boolean;
        FLocalLogPath: string;
        FLocalLogPathDate: TDateTime;
        FLastMessageID: Cardinal;
        FServer: TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer;
        FClient: TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient;
        FClientList: TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList;
        FListener: TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener;
        FPacketToDispatchList: TShaiTrollInterOpCommunicationInterCOMInstancePacketList;
        FDispatcher: TShaiTrollInterOpCommunicationInterCOMInstanceDispatcher;
        FPacketToSendList: TShaiTrollInterOpCommunicationInterCOMInstancePacketList;
        FSender: TShaiTrollInterOpCommunicationInterCOMInstanceSender;
      private
        function PickPacket(AList: TShaiTrollInterOpCommunicationInterCOMInstancePacketList; out APacket: Pointer; out More: Boolean): Boolean;
     
        function GetCurrentModuleFileName: string;
        function MakeError(const Context: string; const ErrorCode: HRESULT): EShaiTrollInterOpCommunicationInterCOMInstanceError;
        procedure WriteLog(const LogName: string; LogType: TShaiTrollInterOpCommunicationInterCOMInstanceEventLogType; const LogTitle: string; LogMessage: string = ''; AddDate: Boolean = True);
        procedure WriteDebug(const LogName: string; const LogTitle: string; LogMessage: string = ''; AddDate: Boolean = True);
        function GetLocalLogPath(): string;
     
        function DebugDummyClient(): Boolean;
        function DebugTraceAllow(): Boolean;
        function DebugTraceCanal(): Boolean;
        function DebugTraceMisc(): Boolean;
      public
        destructor Destroy(); override;
     
        function BuildMessageID: Cardinal;
        procedure AddPacketToDispatch(Packet: Pointer);
        function PickPacketToDispatch(out APacket: Pointer; out More: Boolean): Boolean;
        function DispatchPacket(out Packet: Pointer; More: PBoolean = nil): Boolean;
        procedure AddPacketToSend(Packet: Pointer);
        function PickPacketToSend(out APacket: Pointer; out More: Boolean): Boolean;
     
        function NewClient(ClientID: THandle): Integer;
        function FindClient(ClientID: THandle): TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient;
        procedure DisposeClient(ClientID: THandle);
     
        function StartConnection(ModeServer: WordBool): WordBool;
        function SaisieEvent(const NumRef: WideString; TypeK: Integer; TypeEvent: Integer;
                             const NumEvent_EV_K: WideString): IShaiTrollInterOpEventIDList;
        procedure MajEvent(const NumRef: WideString; TypeK: Integer);
     
        property InterOpEvents: IShaiTrollInterOpEvents read FEvents write FEvents;
        property ModeServer: Boolean read FModeServer;
        property Server: TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer read FServer;
      end;
     
      TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList = class(TThreadList)
      private
        FManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager;
      public
        constructor Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager);
        destructor Destroy(); override;
        procedure Clear();
     
        function NewClient(ClientID: THandle): Integer;
        function FindClient(ClientID: THandle): TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient;
        procedure DisposeClient(ClientID: THandle);
      end;
     
      // Fonctionnalité nécessaire
     
      // Créer un channel serveur réservé à celui qui écoute les demandes :
      // .Permanent
      // - CreateFileMapping Global et MapViewOfFile à chaque lecture du Canal de Demande (code NeoInterOp_Server_Event, NeoInterOp_Server_ShareMem, NeoInterOp_Server_ShareMutex, NeoInterOp_Server_Unique)
      // - Création du Signal de Demande par Event
      // - Thread de Lecture (Attente de l'Event Signal de Demande via WaitForSingleObject)
      // - Création du Mutex du Canal de Demande (return <> 0)
      // - Création d'un Mutex pour déclarer un Serveur Unique (return <> 0 et GetLastError <> ERROR_ALREADY_EXISTS)
      // .Traitement d'une Demande
      // - Lire via CopyMemory sur le MapViewOfFile, on obtient un identifiant
      // - Création du Signal de Réponse par Event (code NeoInterOp_Client_Event_xxxxxxxxxx)
      // - CreateFileMapping Global et MapViewOfFile à chaque écriture du Canal de Réponse (code NeoInterOp_Client_ShareMem_xxxxxxxxxx)
      // - Ecriture via CopyMemory sur le MapViewOfFile
      // - PulseEvent Signal de Réponse
     
      // Créer un channel par client (xxxxxxxxxx = ID du Thread)
      // - CreateFileMapping Global et MapViewOfFile à chaque lecture du Canal de Demande
      // - Création du Signal de Demande par Event
      // - Création du Signal de Réponse par Event (code NeoInterOp_Client_Event_xxxxxxxxxx)
      // - CreateFileMapping Global et MapViewOfFile à chaque écriture (code NeoInterOp_Server_ShareMem)
      // - Section Critique par Mutex lors de l'Ecriture dans le Canal de Demande (code NeoInterOp_Server_ShareMutex)
      // - PulseEvent Signal de Demande
     
     
      PShaiTrollInterOpCommunicationInterCOMInstancePacketHeader = ^TShaiTrollInterOpCommunicationInterCOMInstancePacketHeader;
      TShaiTrollInterOpCommunicationInterCOMInstancePacketHeader = packed record
        SOM: Byte;
        PacketSize: Word; // 64Ko Max !
        SenderID: DWord; // 0 = Serveur sinon Client
        ReceiverID: DWord; // 0 = Serveur sinon Client
        MessageID: Cardinal;
        SendTentative: Byte;
      end;
      TShaiTrollInterOpCommunicationInterCOMInstancePacketBodyType = (pbtCall, pbtReturn, pbtError);
      TShaiTrollInterOpCommunicationInterCOMInstancePacketBody = packed record
        case Operation: ShaiTrollInterOpCOM_TLB.ShaiTrollInterOpDispIDs of
          Event_OnConnecting_DispID:
            (
               StartConnection: record
                 case BodyType: TShaiTrollInterOpCommunicationInterCOMInstancePacketBodyType of
                   pbtCall:
                     (
                       FuncParams: record
                         Connecting: Boolean; // True: Connect, False: Disconnect;
                       end;
                     );
                   pbtReturn:
                     (
                       FuncResult: record
                         Success: Boolean;
                         ClientIndex: Integer;
                       end;
                     );
                   pbtError:
                     (
                       FuncError: record
                         ErrorMessageLen: Word;
                         ErrorMessage: array[0..2000] of Char;
                       end;
                     );
               end;
            );
          Event_OnSaisieEvent_DispID:
            (
               SaisieEvent: record
                 case BodyType: TShaiTrollInterOpCommunicationInterCOMInstancePacketBodyType of
                   pbtCall:
                     (
                        FuncParams: record
                          NumRef: string[10];
                          TypeK: ShaiTrollInterOpCOM_TLB.ShaiTrollInterOpTypeK;
                          TypeEvent: ShaiTrollInterOpCOM_TLB.ShaiTrollInterOpTypeEvent;
                          NumEvent_EV_K: string[2];
                        end;
                     );
                   pbtReturn:
                     (
                       FuncResult: record
                         EventIDListCount: Word;
                         EventIDList: array[0..1000] of Integer;
                         ActiveEventID: Integer;
                         WarningsLen: Word;
                         Warnings: array[0..1000] of Char;
                       end;
                     );
                   pbtError:
                     (
                       FuncError: record
                         ErrorMessageLen: Word;
                         ErrorMessage: array[0..2000] of Char;
                       end;
                     );
               end;
            );
          Event_OnMajEvent_DispID:
            (
               MajEvent: record
                 case BodyType: TShaiTrollInterOpCommunicationInterCOMInstancePacketBodyType of
                   pbtCall:
                     (
                        FuncParams: record
                          NumRef: string[10];
                          TypeK: ShaiTrollInterOpCOM_TLB.ShaiTrollInterOpTypeK;
                        end;
                     );
                   pbtReturn:
                     (
                       FuncResult: record
                       end;
                     );
                   pbtError:
                     (
                       FuncError: record
                         ErrorMessageLen: Word;
                         ErrorMessage: array[0..1000] of Char;
                       end;
                     );
               end;
            );
      end;
      TShaiTrollInterOpCommunicationInterCOMInstancePacketFooter = packed record
        EOM: Byte;
      end;
      PShaiTrollInterOpCommunicationInterCOMInstancePacket = ^TShaiTrollInterOpCommunicationInterCOMInstancePacket;
      TShaiTrollInterOpCommunicationInterCOMInstancePacket = record
        Header: TShaiTrollInterOpCommunicationInterCOMInstancePacketHeader;
        Body: TShaiTrollInterOpCommunicationInterCOMInstancePacketBody;
        Footer: TShaiTrollInterOpCommunicationInterCOMInstancePacketFooter;
      end;
     
      TShaiTrollInterOpCommunicationInterCOMInstanceCanal = class
      private
        FManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager;
        FShareMemory: THandle; // FileMapping
        FSectionCritiqueOnWrite: THandle; // Mutex
        FSignalOnClientRead: THandle; // Event
        FSignalOnServerRead: THandle; // Event
        FSendingDelay: Cardinal;
        FCurrentBuffer: PShaiTrollInterOpCommunicationInterCOMInstancePacketHeader; // Pointeur sur le Fichier Virtuel Partagé en Mémoire
      protected
        FCanalID: DWord;
      protected
        function BuildId(const NameID: string): string; virtual; abstract;
        procedure RaiseLastOSError(const Context: string; const NameID: string; const ErrorCode: HRESULT);
        function MakeError(const Context: string; const NameID: string; const ErrorCode: HRESULT): EShaiTrollInterOpCommunicationInterCOMInstanceError;
     
        function WaitForReadEvent(dwMilliseconds: DWORD): DWORD; virtual; abstract;
        function PulseReadEvent(): BOOL; virtual; abstract;
     
        function WaitRead(SleepDelay: Cardinal): Boolean;
        function BeginRead(): Boolean;
        function Read(Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket): Boolean;
        function EndRead(): Boolean;
     
        function WaitSend(SleepDelay: Cardinal): Boolean;
        function BeginSend(PacketSize: Word): Boolean;
        function Send(Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket): Boolean;
        function EndSend(): Boolean;
      public
        constructor Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager); virtual;
        destructor Destroy(); override;
     
        function ReadPacket(SleepDelay: Cardinal): Boolean;
        function SendPacket(Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket): Boolean;
     
        property Manager: TShaiTrollInterOpCommunicationInterCOMInstanceManager read FManager;
      end;
     
      TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer = class(TShaiTrollInterOpCommunicationInterCOMInstanceCanal)
      private
        FUniqueServer: THandle; // Mutex
      protected
        function BuildId(const NameID: string): string; override;
     
        function WaitForReadEvent(dwMilliseconds: DWORD): DWORD; override;
        function PulseReadEvent(): BOOL; override;
      public
        constructor Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager); override;
        destructor Destroy(); override;
        procedure Connect();
     
        property ServerID: DWord read FCanalID;
      end;
     
      TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient = class(TShaiTrollInterOpCommunicationInterCOMInstanceCanal)
      private
        FConnectingFailed: Boolean; // Tentative de Connexion en Erreur (nécessite un nettoyage tout de même !)
        FConnected: Boolean;
        FClientIndex: Integer;
      protected
        function BuildId(const NameID: string): string; override;
     
        function WaitForReadEvent(dwMilliseconds: DWORD): DWORD; override;
        function PulseReadEvent(): BOOL; override;
      public
        constructor Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager; const AClientID: THandle = 0); reintroduce;
        destructor Destroy(); override;
     
        procedure Connect(DoConnecting: Boolean);
        function SaisieEvent(const NumRef: WideString; TypeK: Integer; TypeEvent: Integer;
                             const NumEvent_EV_K: WideString): IShaiTrollInterOpEventIDList;
        procedure MajEvent(const NumRef: WideString; TypeK: Integer);
     
        property ClientID: DWord read FCanalID;
      end;
     
      TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener = class(TThread)
      private
        FCanalIn: TShaiTrollInterOpCommunicationInterCOMInstanceCanal;
      protected
        procedure Execute(); override;
     
        procedure ProtectThreadErrors(const Context: string);
      public
        constructor Create(ACanalIn: TShaiTrollInterOpCommunicationInterCOMInstanceCanal);
        destructor Destroy(); override;
      end;
     
      TShaiTrollInterOpCommunicationInterCOMInstancePacketList = class(TThreadList)
      public
        destructor Destroy(); override;
        procedure Clear();
      end;
     
      TShaiTrollInterOpCommunicationInterCOMInstanceDispatcher = class(TThread)
      private
        FManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager;
      protected
        procedure Execute(); override;
        procedure ProtectThreadErrors(const Context: string);
      public
        constructor Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager);
     
        property Manager: TShaiTrollInterOpCommunicationInterCOMInstanceManager read FManager;
      end;
     
      TShaiTrollInterOpCommunicationInterCOMInstanceSender = class(TThread)
      private
        FManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager;
      protected
        procedure Execute(); override;
        procedure ProtectThreadErrors(const Context: string);
      public
        constructor Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager);
     
        property Manager: TShaiTrollInterOpCommunicationInterCOMInstanceManager read FManager;
      end;
     
     
    implementation
     
    uses uDelphiUtils;
     
    const
      START_OF_MESSAGE = $FD; // ý - SOM
      END_OF_MESSAGE  = $FE; // þ - EOM
      SHARED_MEMORY_SIZE = SizeOf(TShaiTrollInterOpCommunicationInterCOMInstancePacket);
     
      CANAL_ID_SERVER = 0;
     
    { TShaiTrollInterOpCommunicationInterCOMInstanceManager }
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.StartConnection(ModeServer: WordBool): WordBool;
    begin
      FModeServer := ModeServer;
      FIniFile := TIniFile.Create(ChangeFileExt(GetCurrentModuleFileName(), '.ini'));
     
      if not FModeServer and DebugDummyClient then
      begin
        Result := True;
        Exit;
      end;
     
      FServer := TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer.Create(Self);
      FServer.Connect();
     
      FPacketToDispatchList := TShaiTrollInterOpCommunicationInterCOMInstancePacketList.Create();
      FPacketToSendList := TShaiTrollInterOpCommunicationInterCOMInstancePacketList.Create();
     
      if FModeServer then
      begin
        FClientList := TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList.Create(Self);
        FListener := TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener.Create(FServer);
        FDispatcher := TShaiTrollInterOpCommunicationInterCOMInstanceDispatcher.Create(Self);
        FSender := TShaiTrollInterOpCommunicationInterCOMInstanceSender.Create(Self);
      end
      else
      begin
        FClient := TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient.Create(Self);
        FClient.Connect(True);
      end;
     
      if Assigned(InterOpEvents) then
        Result := InterOpEvents.OnConnecting()
      else
        if FModeServer then
          raise MakeError('EventSink Missing', HResult(ERR_OLE_SERVER_EVENT_SINK_MISSING))
        else
          Result := True;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.SaisieEvent(
      const NumRef: WideString; TypeK, TypeEvent: Integer;
      const NumEvent_EV_K: WideString): IShaiTrollInterOpEventIDList;
    begin
      if FModeServer then
      begin
        if Assigned(InterOpEvents) then
        begin
          try
            Result := InterOpEvents.OnSaisieEvent(NumRef, TypeK, TypeEvent, NumEvent_EV_K);
          except
            on E: Exception do
            begin
              raise MakeError('Exception InterOpEvents.OnSaisieEvent : ' + E.Message, HResult(ERR_OLE_CLIENT_INVALID_SAISIE_EVENT_RESPONSE_FROM_ON_SERVER));
            end;
          end;
        end
        else
          raise MakeError('EventSink Missing', HResult(ERR_OLE_SERVER_EVENT_SINK_MISSING));
      end
      else
      begin
        if DebugDummyClient then
        begin
          Result := CoShaiTrollInterOpEventIDListImpl.Create();
          Result.AddEventID(1000, False);
          Result.AddEventID(1001, True);
          Result.AddEventID(1002, False);
          Result.Warnings := 'DummyClient';
        end
        else
        begin
          Result := FClient.SaisieEvent(NumRef, TypeK, TypeEvent, NumEvent_EV_K);
        end;
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceManager.MajEvent(const NumRef: WideString; TypeK: Integer);
    begin
      if FModeServer then
      begin
        if Assigned(InterOpEvents) then
        begin
          try
            InterOpEvents.OnMajEvent(NumRef, TypeK);
          except
            on E: Exception do
            begin
              raise MakeError('Exception InterOpEvents.MajEvent : ' + E.Message, HResult(ERR_OLE_CLIENT_INVALID_MAJ_EVENT_RESPONSE_FROM_ON_SERVER));
            end;
          end;
        end
        else
          raise MakeError('EventSink Missing', HResult(ERR_OLE_SERVER_EVENT_SINK_MISSING));
      end
      else
      begin
        if not DebugDummyClient then
          FClient.MajEvent(NumRef, TypeK);
      end;
    end;
     
     
    {* ----------------------------------------------------------------------------}
    destructor TShaiTrollInterOpCommunicationInterCOMInstanceManager.Destroy();
    begin
      FreeAndNil(FSender);
      FreeAndNil(FDispatcher);
      FreeAndNil(FListener);
     
      FreeAndNil(FPacketToSendList);
      FreeAndNil(FPacketToDispatchList);
      FreeAndNil(FClientList);
      FreeAndNil(FClient);
      FreeAndNil(FServer);
     
      FreeAndNil(FIniFile);
     
      inherited Destroy();
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.BuildMessageID(): Cardinal;
    begin
      Inc(FLastMessageID);
      Result := FLastMessageID;
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceManager.AddPacketToDispatch(Packet: Pointer);
    begin
      FPacketToDispatchList.Add(Packet);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.PickPacketToDispatch(out APacket: Pointer; out More: Boolean): Boolean;
    begin
      Result := PickPacket(FPacketToDispatchList, APacket, More);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.DispatchPacket(out Packet: Pointer; More: PBoolean = nil): Boolean;
    const
      ERROR_BODY_TYPE = 'Unknown BodyType';
     
      procedure SwitchSenderReceiver(var Header: TShaiTrollInterOpCommunicationInterCOMInstancePacketHeader);
      var
        KeepID: THandle;
      begin
        KeepID := Header.SenderID;
        Header.SenderID := Header.ReceiverID;
        Header.ReceiverID := KeepID;
      end;
     
      procedure DispatchConnecting(var Packet: TShaiTrollInterOpCommunicationInterCOMInstancePacket);
      begin
        Result := False;
     
        case Packet.Body.StartConnection.BodyType of
          pbtCall:
            begin
              try
                if Self.ModeServer then
                begin
                  if Packet.Body.StartConnection.FuncParams.Connecting then
                  begin
                    Packet.Body.StartConnection.FuncResult.ClientIndex := NewClient(Packet.Header.SenderID);
                    Packet.Body.StartConnection.BodyType := pbtReturn;
                    Packet.Body.StartConnection.FuncResult.Success := True;
                    Result := True;
                  end
                  else
                  begin
                    DisposeClient(Packet.Header.SenderID);
                  end;
                end
                else
                  Abort;
              except
                on E: Exception do
                  WriteLog('ERROR_MANAGER_DISPATCH', ltError, 'Error NewClient', E.Message);
              end;
            end;
     
          pbtReturn:
            begin
              if Self.ModeServer then
                WriteLog('ERROR_MANAGER_DISPATCH', ltWarning, 'Unexpected Connecting Return', '');
            end;
     
          pbtError:
            begin
              if Self.ModeServer then
                 WriteLog('ERROR_MANAGER_DISPATCH', ltWarning, 'Unexpected Connecting Error',  Copy(Packet.Body.StartConnection.FuncError.ErrorMessage, 1, Packet.Body.StartConnection.FuncError.ErrorMessageLen));
            end;
        else
          WriteLog('ERROR_MANAGER_DISPATCH', ltError, ERROR_BODY_TYPE);
        end;
      end;
     
      procedure DispatchSaisieEvent(var Packet: TShaiTrollInterOpCommunicationInterCOMInstancePacket);
      var
        AnsiTemp: string;
        EventList: IShaiTrollInterOpEventIDList;
        I: Word;
      begin
        Result := False;
     
        case Packet.Body.SaisieEvent.BodyType of
          pbtCall:
            begin
              try
                if Self.ModeServer then
                begin
                  Packet.Body.SaisieEvent.BodyType := pbtReturn;
     
                  EventList := FEvents.OnSaisieEvent(
                    Packet.Body.SaisieEvent.FuncParams.NumRef,
                    Packet.Body.SaisieEvent.FuncParams.TypeK,
                    Packet.Body.SaisieEvent.FuncParams.TypeEvent,
                    Packet.Body.SaisieEvent.FuncParams.NumRef
                  );
                  try
                    Packet.Body.SaisieEvent.FuncResult.EventIDListCount := Min(High(Packet.Body.SaisieEvent.FuncResult.EventIDList) + 1, EventList.Count);
     
                    for I := Low(Packet.Body.SaisieEvent.FuncResult.EventIDList) to Packet.Body.SaisieEvent.FuncResult.EventIDListCount - 1 do
                      Packet.Body.SaisieEvent.FuncResult.EventIDList[I] := EventList.Item[I];
     
                    Packet.Body.SaisieEvent.FuncResult.ActiveEventID := EventList.ActiveEventID;
     
                    AnsiTemp := EventList.Warnings;
                    Packet.Body.SaisieEvent.FuncResult.WarningsLen := Length(AnsiTemp);
                    CopyMemory(@Packet.Body.SaisieEvent.FuncResult.Warnings, PChar(AnsiTemp), Packet.Body.SaisieEvent.FuncResult.WarningsLen + 1); // le + 1 englobe le Zéro terminal fourni par le type string !
                  finally
                    EventList := nil;
                  end;
     
                  Result := True;
                end
                else
                  Abort;
              except
                on E: Exception do
                begin
                  WriteLog('ERROR_MANAGER_DISPATCH', ltError, 'Error SaisieEvent', E.Message);
     
                  Packet.Body.SaisieEvent.BodyType := pbtError;
     
                  AnsiTemp := E.Message;
                  Packet.Body.SaisieEvent.FuncError.ErrorMessageLen := Length(AnsiTemp);
                  CopyMemory(@Packet.Body.SaisieEvent.FuncError.ErrorMessage, PChar(AnsiTemp), Packet.Body.SaisieEvent.FuncError.ErrorMessageLen + 1); // le + 1 englobe le Zéro terminal fourni par le type string !
     
                  Result := True;
     
                end;
              end;
            end;
     
          pbtReturn:
            begin
              if Self.ModeServer then
                WriteLog('ERROR_MANAGER_DISPATCH', ltWarning, 'Unexpected SaisieEvent Return', '');
            end;
     
          pbtError:
            begin
              if Self.ModeServer then
                WriteLog('ERROR_MANAGER_DISPATCH', ltWarning, 'Unexpected SaisieEvent Error ',  Copy(Packet.Body.SaisieEvent.FuncError.ErrorMessage, 1, Packet.Body.SaisieEvent.FuncError.ErrorMessageLen));
            end;
        end;
      end;
     
      procedure DispatchMajEvent(var Packet: TShaiTrollInterOpCommunicationInterCOMInstancePacket);
      var
        AnsiTemp: string;
      begin
        Result := False;
     
        case Packet.Body.MajEvent.BodyType of
          pbtCall:
            begin
              try
                if Self.ModeServer then
                begin
                  Packet.Body.MajEvent.BodyType := pbtReturn;
                  FEvents.OnMajEvent(Packet.Body.MajEvent.FuncParams.NumRef, Packet.Body.MajEvent.FuncParams.TypeK);
                  Result := True;
                end
                else
                  Abort;
              except
                on E: Exception do
                begin
                  WriteLog('ERROR_MANAGER_DISPATCH', ltError, 'Error MajEvent', E.Message);
     
                  Packet.Body.MajEvent.BodyType := pbtError;
     
                  AnsiTemp := E.Message;
                  Packet.Body.MajEvent.FuncError.ErrorMessageLen := Length(AnsiTemp);
                  CopyMemory(@Packet.Body.MajEvent.FuncError.ErrorMessage, PChar(AnsiTemp), Packet.Body.MajEvent.FuncError.ErrorMessageLen + 1); // le + 1 englobe le Zéro terminal fourni par le type string !
     
                  Result := True;
                end;
              end;
            end;
     
          pbtReturn:
            begin
              if Self.ModeServer then
                WriteLog('ERROR_MANAGER_DISPATCH', ltWarning, 'Unexpected MajEvent Return', '');
            end;
          pbtError:
            begin
              if Self.ModeServer then
                WriteLog('ERROR_MANAGER_DISPATCH', ltWarning, 'Unexpected MajEvent Error ',  Copy(Packet.Body.MajEvent.FuncError.ErrorMessage, 1, Packet.Body.MajEvent.FuncError.ErrorMessageLen));
            end;
        end;
      end;
     
    var
      PacketToDispatch: PShaiTrollInterOpCommunicationInterCOMInstancePacket absolute Packet;
      DummyMore: Boolean;
    begin
      Result := False;
     
      if not Assigned(More) then
        More := @DummyMore;
     
      if PickPacketToDispatch(Packet, More^) then
      begin
        case PacketToDispatch.Body.Operation of
          Event_OnConnecting_DispID: DispatchConnecting(PacketToDispatch^);
          Event_OnSaisieEvent_DispID: DispatchSaisieEvent(PacketToDispatch^);
          Event_OnMajEvent_DispID: DispatchMajEvent(PacketToDispatch^);
        end;
     
        if Result then // un Message Dispatché et en Attente d'Envoi !
        begin
          SwitchSenderReceiver(PacketToDispatch^.Header);
          AddPacketToSend(PacketToDispatch);
        end;
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceManager.AddPacketToSend(Packet: Pointer);
    begin
      FPacketToSendList.Add(Packet);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.PickPacketToSend(out APacket: Pointer; out More: Boolean): Boolean;
    begin
      Result := PickPacket(FPacketToSendList, APacket, More);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.PickPacket(AList: TShaiTrollInterOpCommunicationInterCOMInstancePacketList; out APacket: Pointer; out More: Boolean): Boolean;
    var
      List: TList;
    begin
      Result := False;
      APacket := nil;
      More := False;
     
      List := AList.LockList();
      try
        if List.Count > 0 then
        begin
          APacket := List.First();
          Result := Assigned(APacket);
          List.Delete(0);
     
          More := List.Count > 0;
        end;
      finally
        AList.UnlockList();
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.NewClient(ClientID: THandle): Integer;
    begin
      Result := FClientList.NewClient(ClientID);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.FindClient(ClientID: THandle): TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient;
    begin
      Result := FClientList.FindClient(ClientID);
    end;
     
    {* --------------------------------------------------------------------------- }
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceManager.DisposeClient(ClientID: THandle);
    begin
      FClientList.DisposeClient(ClientID);
    end;
     
    {* --------------------------------------------------------------------------- }
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.GetCurrentModuleFileName(): string;
    begin
      SetLength(Result, MAX_PATH);
      ZeroMemory(@Result[1], MAX_PATH);
      GetModuleFileName(HInstance, @Result[1], MAX_PATH);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.MakeError(const Context: string; const ErrorCode: HRESULT): EShaiTrollInterOpCommunicationInterCOMInstanceError;
    begin
      Result := EShaiTrollInterOpCommunicationInterCOMInstanceError.Create(Context, ErrorCode);
      WriteLog('ERROR_MANAGER', ltError, IntToHex(ErrorCode, 8), Context);
    end;
     
    const
      LOG_TYPES: array[TShaiTrollInterOpCommunicationInterCOMInstanceEventLogType] of string = ('', '[EXCEPTION]', '[ERROR]', '[WARNING]', '');
     
    {* --------------------------------------------------------------------------- }
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceManager.WriteLog(const LogName: string; LogType: TShaiTrollInterOpCommunicationInterCOMInstanceEventLogType; const LogTitle: string; LogMessage: string = ''; AddDate: Boolean = True);
    var
      LogFile: file;
      DirLog, NameFile, TimeLog: string;
      Buf: string;
    const
      LogPrefixe = 'LOG_';
      LogExt = '.txt';
    begin
      try
        if AddDate then
          TimeLog := FormatDateTime('dd/mm/yyyy hh:nn:ss:zzz', Now());
     
        DirLog := GetLocalLogPath();
     
        if not DirectoryExists(DirLog) then
          ForceDirectories(DirLog);
     
        NameFile := DirLog + LogPrefixe + IfThen(ModeServer, 'SERVER_', 'CLIENT_') + LogName + FormatDateTime('_yyyyddmm', Now()) + LogExt;
        try
         AssignFile(LogFile, NameFile);
         try
           if FileExists(NameFile) then
           begin
             Reset(LogFile, 1);
             Seek(LogFile, FileSize(LogFile));
           end
           else
             ReWrite(LogFile, 1);
     
           try
             if LogMessage > '' then
               Buf := LOG_TYPES[LogType] + #9 + LogTitle + ' :'#9 + LogMessage + #13#10
             else
               Buf := LOG_TYPES[LogType] + #9 + LogTitle + #13#10;
     
             if AddDate then
               Buf := TimeLog + #9', ' + Buf;
     
             // Buf[1] car BlockWrite écrit n octets à partir de la position Buf[1] !
             BlockWrite(LogFile, Buf[1], Length(Buf));
            except
               Exit;
            end;
          finally
            CloseFile(LogFile);
          end;
        except
          Exit;
        end;
      except
        Exit;
      end;
    end;
     
    {* --------------------------------------------------------------------------- }
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceManager.WriteDebug(const LogName: string; const LogTitle: string; LogMessage: string = ''; AddDate: Boolean = True);
    begin
      if DebugTraceAllow then
      begin
        if LogName = 'MISC' then
          if not DebugTraceMisc() then
            Exit;
     
        if LogName = 'CANAL' then
          if not DebugTraceCanal() then
            Exit;
     
        WriteLog('DEBUG_' + LogName, ltInfo, LogTitle, LogMessage);
      end;
    end;
     
    {* --------------------------------------------------------------------------- }
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.GetLocalLogPath(): string;
    var
      YearMonthDay: string;
      DirLog: string;
    begin
      // Un Fichier Log par Jour
      if FLocalLogPathDate <= Date() - 1 then
      begin
        // Un Dossier Log par Mois
        FLocalLogPathDate := Date();
        YearMonthDay := FormatDateTime('YYYYMM\YYYYMMDD', Now());
        DirLog := ExtractFilePath(GetCurrentModuleFileName()) + 'LOG\' + YearMonthDay;
        if not DirectoryExists(DirLog) then
          ForceDirectories(DirLog);
        FLocalLogPath := IncludeTrailingPathDelimiter(DirLog);
      end;
     
      Result := FLocalLogPath;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.DebugDummyClient: Boolean;
    begin
      Result := StrToBoolDef(FIniFile.ReadString('Debug', 'DummyClient', ''), False);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.DebugTraceAllow: Boolean;
    begin
       Result := StrToBoolDef(FIniFile.ReadString('Debug', 'TraceAllow', ''), False);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.DebugTraceCanal: Boolean;
    begin
       Result := StrToBoolDef(FIniFile.ReadString('Debug', 'TraceCanal', ''), False);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceManager.DebugTraceMisc: Boolean;
    begin
       Result := StrToBoolDef(FIniFile.ReadString('Debug', 'TraceMisc', ''), False);
    end;
     
    { TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList }
     
    {* ----------------------------------------------------------------------------}
    constructor TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList.Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager);
    begin
      inherited Create();
     
      FManager := AManager;
    end;
     
     
    {* ----------------------------------------------------------------------------}
    destructor TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList.Destroy();
    begin
      Clear();
     
      inherited Destroy();
    end;
     
    {* ----------------------------------------------------------------------------}
    type
      PShaiTrollInterOpCommunicationInterCOMInstanceCanalClientListItem = ^TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientListItem;
      TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientListItem = record
        ClientID: DWord;
        Client: TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient;
        ClientListener: TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener;
      end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList.Clear();
    var
      List: TList;
      I: Integer;
    begin
      List := LockList();
      try
        for I := 0 to List.Count - 1 do
          Dispose(PShaiTrollInterOpCommunicationInterCOMInstanceCanalClientListItem(List.Items[I]));
     
        List.Clear();
      finally
        UnlockList();
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList.NewClient(ClientID: THandle): Integer;
    var
      List: TList;
      TmpClient: TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient;
      TmpClientListener: TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener;
      ItemList: PShaiTrollInterOpCommunicationInterCOMInstanceCanalClientListItem;
    begin
      List := LockList();
      try
        for Result := 0 to List.Count - 1 do
          if ClientID = PShaiTrollInterOpCommunicationInterCOMInstanceCanalClientListItem(List.Items[Result])^.ClientID then
            Exit;
     
        Result := -1;
     
        FManager.WriteDebug('MISC', 'NewClient', IntToStr(ClientID));
        TmpClient := TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient.Create(FManager, ClientID);
        try
          TmpClientListener := TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener.Create(TmpClient);
          try
            New(ItemList);
            try
              ItemList.ClientID := ClientID;
              ItemList.Client := TmpClient;
              ItemList.ClientListener := TmpClientListener;
              Result := List.Add(ItemList);
     
              FManager.WriteDebug('MISC', 'NewClient Added', IntToStr(ClientID));
            except
              Dispose(ItemList);
            end;
          except
            TmpClientListener.Free();
          end;
        except
          TmpClient.Free();
        end;
      finally
        UnlockList();
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList.FindClient(ClientID: THandle): TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient;
    var
      List: TList;
      I: Integer;
    begin
      List := LockList();
      try
        for I := 0 to List.Count - 1 do
        begin
          if ClientID = PShaiTrollInterOpCommunicationInterCOMInstanceCanalClientListItem(List.Items[I])^.ClientID then
          begin
            Result := PShaiTrollInterOpCommunicationInterCOMInstanceCanalClientListItem(List.Items[I])^.Client;
            Exit;
          end;
        end;
     
        Result := nil;
      finally
        UnlockList();
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceCanalClientList.DisposeClient(ClientID: THandle);
    var
      List: TList;
      I: Integer;
      ItemList: PShaiTrollInterOpCommunicationInterCOMInstanceCanalClientListItem;
    begin
      FManager.WriteDebug('MISC', 'DisposeClient', IntToStr(ClientID));
     
      List := LockList();
      try
        for I := 0 to List.Count - 1 do
        begin
          ItemList := PShaiTrollInterOpCommunicationInterCOMInstanceCanalClientListItem(List.Items[I]);
          if ClientID = ItemList^.ClientID then
          begin
            List.Delete(I);
     
            FreeAndNil(ItemList^.Client);
            FreeAndNil(ItemList^.ClientListener);
            Dispose(ItemList);
     
            FManager.WriteDebug('MISC', 'DisposeClient Deleted', IntToStr(ClientID));
            Exit;
          end;
        end;
      finally
        UnlockList();
      end;
    end;
     
    { TShaiTrollInterOpCommunicationInterCOMInstanceCanal }
     
    {* ----------------------------------------------------------------------------}
    constructor TShaiTrollInterOpCommunicationInterCOMInstanceCanal.Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager);
    begin
      inherited Create();
     
      FManager := AManager;
     
      if Manager.ModeServer then
        FSendingDelay := 200
      else
        FSendingDelay := INFINITE;
     
      // On Crée un Fichier Virtuel en Mémoire
      // Si  Fichier Virtuel en Mémoire porte le même nom, il sera partagé !
      FShareMemory := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0, SHARED_MEMORY_SIZE, PChar(BuildId('ShareMem')));
      if FShareMemory = 0 then
        RaiseLastOSError('CreateFileMapping', 'ShareMem', HResult(ERR_OLE_CREATE_SHARE_MEM));
     
      // On sécurise l'Ecriture dans le Fichier Virtuel en Mémoire
      FSectionCritiqueOnWrite := CreateMutex(nil, False, PChar(BuildId('ShareMutex')));
      if FSectionCritiqueOnWrite = 0 then
        RaiseLastOSError('CreateMutex', 'ShareMutex', HResult(ERR_OLE_CREATE_SHARE_MUTEX));
     
      // On se branche sur l'Event indiquant que le Client doit lire ShareMem
      FSignalOnClientRead := CreateEvent(nil, True, False, PChar(BuildId('EventClientRead')));
      if FSignalOnClientRead = 0 then
        RaiseLastOSError('CreateEvent', 'EventClientRead', HResult(ERR_OLE_CREATE_EVENT_CLIENT_READ));
     
      // On se branche sur l'Event indiquant que le Server doit lire ShareMem
      FSignalOnServerRead := CreateEvent(nil, True, False, PChar(BuildId('EventServerRead')));
      if FSignalOnServerRead = 0 then
        RaiseLastOSError('CreateEvent', 'EventServerRead', HResult(ERR_OLE_CREATE_EVENT_SERVER_READ));
    end;
     
    {* ----------------------------------------------------------------------------}
    destructor TShaiTrollInterOpCommunicationInterCOMInstanceCanal.Destroy;
    begin
      if FSignalOnServerRead > 0 then
        CloseHandle(FSignalOnServerRead);
      if FSignalOnClientRead > 0 then
        CloseHandle(FSignalOnClientRead);
      if FSectionCritiqueOnWrite > 0 then
        CloseHandle(FSectionCritiqueOnWrite);
      if FShareMemory > 0 then
        CloseHandle(FShareMemory);
     
      inherited Destroy();
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.ReadPacket(SleepDelay: Cardinal): Boolean;
    var
      Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket;
    begin
      // Attente d'un Message,
      // True, un Message est là !
      // False, pas de Message mais on réagit pour qu'un WaitFor n'attende pas une réponse qui n'arrivera jamais !
      if WaitRead(SleepDelay) then
      begin
        Result := True; // On signale jusqu'un Message a été Dispatché !
     
        // On récupère un pointeur pour pouvoir lire la mémoire.
        if BeginRead() then
        begin
          try
            New(Packet); // Ne pas oublier le Dispose plus tard dans le code !
            try
              ZeroMemory(Packet, SizeOf(Packet^));
     
              if Read(Packet) then
                Manager.AddPacketToDispatch(Packet)
              else
                raise MakeError('Error on Canal.Dispatch.Read', 'Error', HResult(ERR_OLE_CANAL_DISPATCH_READ));
            except
              on E: Exception do
              begin
                Dispose(Packet);
     
                raise;
              end;
            end;
          finally
            if not EndRead() then
              raise MakeError('Error on Canal.Dispatch.EndRead', 'Error', HResult(ERR_OLE_CANAL_DISPATCH_ENDREAD));
          end;
        end
        else
          raise MakeError('Error on Canal.Dispatch.BeginRead', 'Error', HResult(ERR_OLE_CANAL_DISPATCH_BEGINREAD));
      end
      else
        Result := False; // Pas de Message
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.SendPacket(Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket): Boolean;
    begin
      if WaitSend(FSendingDelay) then
      begin
        if BeginSend(Packet.Header.PacketSize) then
        begin
          try
            Result := Send(Packet); // Message Envoyé !
          finally
            if not EndSend() then
              raise MakeError('Error on Canal.SendPacket.EndSend', 'Error', HResult(ERR_OLE_CANAL_ENDSEND));
          end;
        end
        else
          raise MakeError('Error on Canal.SendPacket.BeginSend', 'Error', HResult(ERR_OLE_CANAL_BEGINSEND));
      end
      else
        Result := False; // Le Canal n'est pas disponible dans le Délai imparti
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceCanal.RaiseLastOSError(const Context: string; const NameID: string; const ErrorCode: HRESULT);
    var
      S: string;
    begin
      try
        SysUtils.RaiseLastOSError();
      except
        on E: Exception do
        begin
          S := Format('Exception %s : "%s" during "%s" [ID: %s]', [E.ClassName, E.Message, Context, BuildId(NameID)]);
          Manager.WriteLog('ERROR_OS', ltException, IntToHex(ErrorCode, 8), S);
     
          raise EShaiTrollInterOpCommunicationInterCOMInstanceError.Create(S, ErrorCode);
        end;
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.MakeError(const Context: string; const NameID: string; const ErrorCode: HRESULT): EShaiTrollInterOpCommunicationInterCOMInstanceError;
    var
      S: string;
    begin
      S := Format('%s [ID: %s]', [Context, BuildId(NameID)]);
      Result := EShaiTrollInterOpCommunicationInterCOMInstanceError.Create(S, ErrorCode);
      Manager.WriteLog('ERROR_CANAL', ltError, IntToHex(ErrorCode, 8), S);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.WaitRead(SleepDelay: Cardinal): Boolean;
    begin
      Manager.WriteDebug('CANAL', Format('WaitRead [ID: %s]', [BuildId('')]), IntToStr(SleepDelay));
     
      Result := WaitForReadEvent(SleepDelay) = WAIT_OBJECT_0;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.BeginRead(): Boolean;
    begin
      Manager.WriteDebug('CANAL', Format('BeginRead [ID: %s]', [BuildId('')]), '');
     
      FCurrentBuffer := MapViewOfFile(FShareMemory, FILE_MAP_READ, 0, 0, SHARED_MEMORY_SIZE);
      Result := Assigned(FCurrentBuffer);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.Read(Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket): Boolean;
    var
      lpData: PByte;
      BodySize: Integer;
    begin
      Manager.WriteDebug('CANAL', Format('Read [ID: %s]', [BuildId('')]), '');
     
      lpData := PByte(FCurrentBuffer);
      BodySize := FCurrentBuffer^.PacketSize - SizeOf(Packet^.Header) - SizeOf(Packet^.Footer);
      if (Low(Word) < BodySize) and (BodySize <= High(Word)) then
      begin
        CopyMemory(@Packet^.Header, lpData, SizeOf(Packet.Header));
        Inc(lpData, SizeOf(Packet.Header));
     
        CopyMemory(@Packet^.Body, lpData, BodySize);
        Inc(lpData, BodySize);
     
        CopyMemory(@Packet^.Footer, lpData, SizeOf(Packet.Footer));
     
        Result := (Packet^.Header.SOM = START_OF_MESSAGE) and (Packet^.Footer.EOM = END_OF_MESSAGE);
     
        if Result then
          Manager.WriteDebug('CANAL', Format('Read OK [ID: %s - Message ID: %d]', [BuildId(''), Packet.Header.MessageID]), '');
      end
      else
        Result := False;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.EndRead: Boolean;
    begin
      Manager.WriteDebug('CANAL', Format('EndRead [ID: %s]', [BuildId('')]), '');
     
      Result := UnmapViewOfFile(FCurrentBuffer);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.WaitSend(SleepDelay: Cardinal): Boolean;
    begin
      Manager.WriteDebug('CANAL', Format('WaitSend [ID: %s]', [BuildId('')]), IntToStr(SleepDelay));
     
      Result := WaitForSingleObject(FSectionCritiqueOnWrite, SleepDelay) = WAIT_OBJECT_0;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.BeginSend(PacketSize: Word): Boolean;
    begin
      Manager.WriteDebug('CANAL', Format('BeginSend [ID: %s]', [BuildId('')]), IntToStr(PacketSize));
     
      FCurrentBuffer := MapViewOfFile(FShareMemory, FILE_MAP_WRITE, 0, 0, PacketSize);
      Result := Assigned(FCurrentBuffer);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.Send(Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket): Boolean;
    var
      lpData: PByte;
      BodySize: Integer;
    begin
      Manager.WriteDebug('CANAL', Format('Send [ID: %s - Message ID: %d]', [BuildId(''), Packet.Header.MessageID]));
     
      lpData := PByte(FCurrentBuffer);
      BodySize := Packet^.Header.PacketSize - SizeOf(Packet^.Header) - SizeOf(Packet^.Footer);
      if (Low(Word) < BodySize) and (BodySize <= High(Word)) then
      begin
        CopyMemory(lpData, @Packet.Header, SizeOf(Packet.Header));
        Inc(lpData, SizeOf(Packet.Header));
     
        CopyMemory(lpData, @Packet.Body, BodySize);
        Inc(lpData, BodySize);
     
        CopyMemory(lpData, @Packet.Footer, SizeOf(Packet.Footer));
     
        Result := (Packet.Header.SOM = START_OF_MESSAGE) and (Packet.Footer.EOM = END_OF_MESSAGE);
      end
      else
        Result := False;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanal.EndSend: Boolean;
    begin
      Manager.WriteDebug('CANAL', Format('EndSend [ID: %s]', [BuildId('')]));
     
      UnmapViewOfFile(FCurrentBuffer);
      PulseReadEvent();
      Result := ReleaseMutex(FSectionCritiqueOnWrite);
      if not Result then
        Result := GetLastError() = ERROR_ALREADY_EXISTS;
    end;
     
    { TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer }
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer.Connect();
    begin
      // On vérifie qu'un Serveur n'est pas déjà lancé
      FUniqueServer := CreateMutex(nil, False, PChar(BuildId('Unique')));
      if FUniqueServer > 0 then
      begin
        if Manager.ModeServer then
        begin
          if GetLastError() = ERROR_ALREADY_EXISTS then
            RaiseLastOSError('CreateMutex', 'Not_Unique', HResult(ERR_OLE_SERVER_NOT_UNIQUE_MUTEX));
        end
        else
        begin
          try
            if GetLastError() <> ERROR_ALREADY_EXISTS then
              RaiseLastOSError('CreateMutex', 'Not_Exists_Unique', HResult(ERR_OLE_CLIENT_NOT_ALREADY_EXISTS_SERVER_UNIQUE_MUTEX));
          finally
            CloseHandle(FUniqueServer);
            FUniqueServer := 0;
          end;
        end;
      end
      else
      begin
        if Manager.ModeServer then
          RaiseLastOSError('CreateMutex', 'Unique', HResult(ERR_OLE_SERVER_CREATE_MUTEX))
        else
          RaiseLastOSError('CreateMutex', 'Unique', HResult(ERR_OLE_CLIENT_NOT_CREATE_SERVER_UNIQUE_MUTEX));
      end;
    end;
     
     
    {* ----------------------------------------------------------------------------}
    constructor TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer.Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager);
    begin
      FCanalID := CANAL_ID_SERVER;
     
      inherited Create(AManager);
    end;
     
    {* ----------------------------------------------------------------------------}
    destructor TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer.Destroy;
    begin
      if FUniqueServer > 0 then
        CloseHandle(FUniqueServer);
     
      inherited Destroy();
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer.BuildId(const NameID: string): string;
    begin
      if NameID <> '' then
        Result := Format('NeoInterOp_Server_%s', [NameID])
      else
        Result := 'Server';
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer.WaitForReadEvent(dwMilliseconds: DWORD): DWORD;
    begin
      Result := WaitForSingleObject(FSignalOnServerRead, dwMilliseconds);
      if Result = WAIT_OBJECT_0 then
        ResetEvent(FSignalOnServerRead);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanalServer.PulseReadEvent: BOOL;
    begin
      Result := PulseEvent(FSignalOnServerRead);
    end;
     
    { TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient }
     
    {* ----------------------------------------------------------------------------}
    constructor TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient.Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager; const AClientID: THandle = 0);
    begin
      if AClientID = 0 then
        FCanalID := GetCurrentThreadId()
      else
        FCanalID := AClientID;
     
      FClientIndex := -1;
     
      inherited Create(AManager);
    end;
     
    {* ----------------------------------------------------------------------------}
    destructor TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient.Destroy;
    begin
      try
        if FConnectingFailed or FConnected then
          Connect(False);
      except
        on E: Exception do
          Manager.WriteLog('ERROR_CANAL', ltException, 'CanalClient.Destroy', E.Message);
      end;
     
      inherited Destroy();
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient.Connect(DoConnecting: Boolean);
    var
      Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket;
      P: Pointer;
      ReceivedPacket: PShaiTrollInterOpCommunicationInterCOMInstancePacket absolute P;
    begin
      FClientIndex := -1;
      if FConnected then
        Exit;
     
      try
        New(Packet);
        try
          ZeroMemory(Packet, SizeOf(Packet^));
          Packet.Header.SOM := START_OF_MESSAGE;
          Packet.Header.PacketSize := SizeOf(Packet.Header) + SizeOf(Packet.Body.Operation) + SizeOf(Packet.Body.StartConnection) + SizeOf(Packet.Footer);
          Packet.Header.SenderID := ClientID;
          Packet.Header.ReceiverID := CANAL_ID_SERVER;
          Packet.Header.MessageID := Manager.BuildMessageID();
          Packet.Body.Operation := Event_OnConnecting_DispID;
          Packet.Body.StartConnection.BodyType := pbtCall;
          Packet.Body.StartConnection.FuncParams.Connecting := DoConnecting;
          Packet.Footer.EOM := END_OF_MESSAGE;
     
          if Manager.Server.SendPacket(Packet) then
          begin
            if not DoConnecting then
            begin
              FConnectingFailed := False;
              FConnected := False;
              Manager.WriteLog('MISC', ltInfo, 'Connection Stopped Notified', IntToStr(ClientID));
              Exit;
            end;
     
            try
              if ReadPacket(10000) then // Attente du Packet, pas plus de 10 secondes, c'est déjà bien trop long !
              begin
                ReceivedPacket := nil;
                try
                  Manager.DispatchPacket(P); // Récupération du Nouveau Packet P => ReceivedPacket
                  if Assigned(ReceivedPacket) and
                    (ReceivedPacket.Header.SenderID = CANAL_ID_SERVER) and
                    (ReceivedPacket.Header.ReceiverID = ClientID) and
                    (ReceivedPacket.Body.Operation = Event_OnConnecting_DispID) and
                    (ReceivedPacket.Body.StartConnection.BodyType = pbtReturn) and
                    (ReceivedPacket.Body.StartConnection.FuncResult.Success)
                    then
                  begin
                    FClientIndex := ReceivedPacket.Body.StartConnection.FuncResult.ClientIndex;
                    FConnectingFailed := False;
                    FConnected := True;
                    Manager.WriteLog('MISC', ltInfo, 'Connection Success', IntToStr(ClientID));
                  end
                  else
                    raise MakeError('Client not Connect on Server', 'Connect', HResult(ERR_OLE_CLIENT_INVALID_CONNECT_ON_SERVER));
                finally
                  if Assigned(ReceivedPacket) then
                    Dispose(ReceivedPacket);
                end;
              end
              else
                raise MakeError('Client not Receive "Connecting Response" From Server', 'Connect', HResult(ERR_OLE_CLIENT_NOT_RECEIVE_CONNECTING_RESPONSE_FROM_SERVER));
            except
              on E: Exception do
              begin
                Manager.WriteLog('MISC', ltInfo, 'Connection Cancel', IntToStr(ClientID));
                FConnectingFailed := True;
     
                raise;
              end;
            end;
          end
          else
          begin
            if DoConnecting then
            begin
              raise MakeError('Client not Send "Connecting Message" to Server', 'Connect', HResult(ERR_OLE_CLIENT_NOT_SEND_CONNECTING_MESSAGE_FROM_SERVER))
            end
            else
            begin
              Manager.WriteLog('MISC', ltWarning, 'Connection Stopped Not Advertise', IntToStr(ClientID));
              FConnectingFailed := False;
              FConnected := False;
            end;
          end;
        finally
          if Assigned(Packet) then
            Dispose(Packet);
        end;
      except
        on EIE: EShaiTrollInterOpCommunicationInterCOMInstanceError do
          raise;
     
        on E: Exception do
          raise MakeError('Unexpected Error on Connect : ' +  E.Message, 'Connect', HResult(ERR_OLE_CLIENT_NOT_CONNECT));
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient.SaisieEvent(
      const NumRef: WideString; TypeK, TypeEvent: Integer;
      const NumEvent_EV_K: WideString): IShaiTrollInterOpEventIDList;
     
      procedure ConvertArrayToIntf(const ArrayList: array of Integer; ArrayListCount: Word; ActiveID: Integer);
      var
        I: Word;
      begin
        Result := CoShaiTrollInterOpEventIDListImpl.Create();
     
        for I := Low(ArrayList) to ArrayListCount - 1 do
          Result.AddEventID(ArrayList[I], ArrayList[I] = ActiveID);
      end;
     
    var
      Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket;
      P: Pointer;
      ReceivedPacket: PShaiTrollInterOpCommunicationInterCOMInstancePacket absolute P;
    begin
      Result := nil;
      try
        New(Packet);
        try
          ZeroMemory(Packet, SizeOf(Packet^));
          Packet.Header.SOM := START_OF_MESSAGE;
          Packet.Header.PacketSize := SizeOf(Packet.Header) + SizeOf(Packet.Body.Operation) + SizeOf(Packet.Body.SaisieEvent) + SizeOf(Packet.Footer);
          Packet.Header.SenderID := ClientID;
          Packet.Header.ReceiverID := CANAL_ID_SERVER;
          Packet.Header.MessageID := Manager.BuildMessageID();
          Packet.Body.Operation := Event_OnSaisieEvent_DispID;
          Packet.Body.SaisieEvent.BodyType := pbtCall;
          Packet.Body.SaisieEvent.FuncParams.NumRef := NumRef;
          Packet.Body.SaisieEvent.FuncParams.TypeK := TypeK;
          Packet.Body.SaisieEvent.FuncParams.TypeEvent := TypeEvent;
          Packet.Body.SaisieEvent.FuncParams.NumEvent_EV_K := NumEvent_EV_K;
          Packet.Footer.EOM := END_OF_MESSAGE;
     
          if SendPacket(Packet) then // Envoi sur le Channel Client réservé et attente de la réponse sur le même Canal !
          begin
            // Plus le nombre d'Event est important plus cela rame !
            if ReadPacket(10000 + FClientIndex * 500) then // Attente du Packet, au moins 10 secondes et plus si bcp de client, c'est déjà bien trop long !
            begin
              ReceivedPacket := nil;
              try
                Manager.DispatchPacket(P); // Récupération du Nouveau Packet P => ReceivedPacket
                if Assigned(ReceivedPacket) and
                  (ReceivedPacket.Header.SenderID = CANAL_ID_SERVER) and
                  (ReceivedPacket.Header.ReceiverID = ClientID) and
                  (ReceivedPacket.Body.Operation = Event_OnSaisieEvent_DispID) then
                begin
                  case ReceivedPacket.Body.SaisieEvent.BodyType of
                    pbtCall: raise MakeError('Client Receive an "Unexpected Call SaisieEvent Response" From Server', 'SaisieEvent', HResult(ERR_OLE_CLIENT_INVALID_SAISIE_EVENT_RESPONSE_FROM_ON_SERVER));
                    pbtReturn :
                      begin
                        try
                          ConvertArrayToIntf(ReceivedPacket.Body.SaisieEvent.FuncResult.EventIDList, ReceivedPacket.Body.SaisieEvent.FuncResult.EventIDListCount, ReceivedPacket.Body.SaisieEvent.FuncResult.ActiveEventID);
                          Result.Warnings := Copy(ReceivedPacket.Body.SaisieEvent.FuncResult.Warnings, 1, ReceivedPacket.Body.SaisieEvent.FuncResult.WarningsLen);
                        except
                          on E: Exception do
                          begin
                            Result := nil;
                            raise;
                          end;
                        end;
                      end;
                    pbtError: raise MakeError('Client Receive an "SaisieEvent Error Response" From Server : ' + Copy(ReceivedPacket.Body.SaisieEvent.FuncError.ErrorMessage, 1, ReceivedPacket.Body.SaisieEvent.FuncError.ErrorMessageLen), 'SaisieEvent', HResult(ERR_OLE_CLIENT_INVALID_SAISIE_EVENT_RESPONSE_FROM_ON_SERVER));
                   end;
                end
                else
                  raise MakeError('Client Receive an "Invalid SaisieEvent Response" From Server', 'SaisieEvent', HResult(ERR_OLE_CLIENT_INVALID_SAISIE_EVENT_RESPONSE_FROM_ON_SERVER));
              finally
                if Assigned(ReceivedPacket) then
                  Dispose(ReceivedPacket);
              end;
            end
            else
              raise MakeError('Client not Receive "SaisieEvent Response" From Server', 'SaisieEvent', HResult(ERR_OLE_CLIENT_NOT_RECEIVE_SAISIE_EVENT_RESPONSE_FROM_SERVER));
          end
          else
            raise MakeError('Client not Send "SaisieEvent Message" to Server', 'Connect', HResult(ERR_OLE_CLIENT_NOT_SEND_SAISIE_EVENT_MESSAGE_FROM_SERVER));
        finally
          if Assigned(Packet) then
            Dispose(Packet);
        end;
      except
        on EIE: EShaiTrollInterOpCommunicationInterCOMInstanceError do
          raise;
     
        on E: Exception do
          raise MakeError('Unexpected Error on SaisieEvent : ' + E.Message, 'SaisieEvent', HResult(ERR_OLE_CLIENT_UNEXPECTED_ERROR_SAISIE_EVENT));
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient.MajEvent(const NumRef: WideString; TypeK: Integer);
    var
      Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket;
      P: Pointer;
      ReceivedPacket: PShaiTrollInterOpCommunicationInterCOMInstancePacket absolute P;
    begin
      try
        New(Packet);
        try
          ZeroMemory(Packet, SizeOf(Packet^));
          Packet.Header.SOM := START_OF_MESSAGE;
          Packet.Header.PacketSize := SizeOf(Packet.Header) + SizeOf(Packet.Body.Operation) + SizeOf(Packet.Body.MajEvent) + SizeOf(Packet.Footer);
          Packet.Header.SenderID := ClientID;
          Packet.Header.ReceiverID := CANAL_ID_SERVER;
          Packet.Header.MessageID := Manager.BuildMessageID();
          Packet.Body.Operation := Event_OnMajEvent_DispID;
          Packet.Body.MajEvent.BodyType := pbtCall;
          Packet.Body.MajEvent.FuncParams.NumRef := NumRef;
          Packet.Body.MajEvent.FuncParams.TypeK := TypeK;
          Packet.Footer.EOM := END_OF_MESSAGE;
     
          if SendPacket(Packet) then // Envoi sur le Channel Client réservé et attente de la réponse sur le même Canal !
          begin
            // Plus le nombre d'Event est important plus MajEvent rame ! mois d'une seconde pour un dossier "normal", disons une demi-secondes par tranche de 50 Event
            if ReadPacket(15000 + FClientIndex * 750) then // Attente du Packet, au moins 15 secondes et plus si bcp de client, c'est déjà bien trop long !
            begin
              Manager.DispatchPacket(P); // Récupération du Nouveau Packet P => ReceivedPacket
              try
                if Assigned(ReceivedPacket) and
                  (ReceivedPacket.Header.SenderID = CANAL_ID_SERVER) and
                  (ReceivedPacket.Header.ReceiverID = ClientID) and
                  (ReceivedPacket.Body.Operation = Event_OnMajEvent_DispID) then
                begin
                  case ReceivedPacket.Body.SaisieEvent.BodyType of
                    pbtCall: raise MakeError('Client Receive an "Unexpected Call MajEvent Response" From Server', 'MajEvent', HResult(ERR_OLE_CLIENT_INVALID_MAJ_EVENT_RESPONSE_FROM_ON_SERVER));
                    pbtReturn: Exit;
                    pbtError: raise MakeError('Client Receive an "MajEvent Error Response" From Server : ' + Copy(ReceivedPacket.Body.SaisieEvent.FuncError.ErrorMessage, 1, ReceivedPacket.Body.SaisieEvent.FuncError.ErrorMessageLen), 'SaisieEvent', HResult(ERR_OLE_CLIENT_INVALID_SAISIE_EVENT_RESPONSE_FROM_ON_SERVER));
                   end;
                end
                else
                  raise MakeError('Client Receive an "Invalid MajEvent Response" From Server', 'MajEvent', HResult(ERR_OLE_CLIENT_INVALID_MAJ_EVENT_RESPONSE_FROM_ON_SERVER));
              finally
                if Assigned(ReceivedPacket) then
                  Dispose(ReceivedPacket);
              end;
            end
            else
              raise MakeError('Client not Receive "MajEvent Response" From Server', 'MajEvent', HResult(ERR_OLE_CLIENT_NOT_RECEIVE_MAJ_EVENT_RESPONSE_FROM_SERVER));
          end
          else
            raise MakeError('Client not Send "MajEvent Message" to Server', 'Connect', HResult(ERR_OLE_CLIENT_NOT_SEND_MAJ_EVENT_MESSAGE_FROM_SERVER));
        finally
          if Assigned(Packet) then
            Dispose(Packet);
        end;
      except
        on EIE: EShaiTrollInterOpCommunicationInterCOMInstanceError do
          raise;
     
        on E: Exception do
          raise MakeError('Unexpected Error on MajEvent : ' + E.Message, 'MajEvent', HResult(ERR_OLE_CLIENT_UNEXPECTED_ERROR_MAJ_EVENT));
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient.BuildId(const NameID: string): string;
    begin
      if NameID <> '' then
        Result := Format('NeoInterOp_Client_%s_%d', [NameID, ClientID])
      else
        Result := Format('Client_%d', [ClientID]);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient.WaitForReadEvent(dwMilliseconds: DWORD): DWORD;
    var
      Signal: THandle;
    begin
      if Manager.ModeServer then
        Signal := FSignalOnServerRead
      else
        Signal := FSignalOnClientRead;
     
      Result := WaitForSingleObject(Signal, dwMilliseconds);
      if Result = WAIT_OBJECT_0 then
        ResetEvent(Signal);
    end;
     
    {* ----------------------------------------------------------------------------}
    function TShaiTrollInterOpCommunicationInterCOMInstanceCanalClient.PulseReadEvent: BOOL;
    begin
      if Manager.ModeServer then
        Result := PulseEvent(FSignalOnClientRead)
      else
        Result := PulseEvent(FSignalOnServerRead);
    end;
     
    { TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener }
     
    {* ----------------------------------------------------------------------------}
    constructor TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener.Create(ACanalIn: TShaiTrollInterOpCommunicationInterCOMInstanceCanal);
    begin
      inherited Create(True);
     
      FCanalIn := ACanalIn;
     
      Resume();
    end;
     
    {* ----------------------------------------------------------------------------}
    destructor TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener.Destroy;
    begin
      TerminateThread(Self.Handle, 0);
     
      inherited Destroy();
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener.Execute();
    begin
      while not Terminated do
      begin
        try
          FCanalIn.ReadPacket(INFINITE);
        except
          on E: Exception do
            ProtectThreadErrors(Format('Exception %s : "%s" during "Listener"', [E.ClassName, E.Message]));
        end;
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceCanalListener.ProtectThreadErrors(const Context: string);
    begin
      FCanalIn.Manager.WriteLog('ERROR_THREAD_LISTENER', ltException, 'Thread Error', Context);
    end;
     
    { TShaiTrollInterOpCommunicationInterCOMInstancePacketList }
     
    {* ----------------------------------------------------------------------------}
    destructor TShaiTrollInterOpCommunicationInterCOMInstancePacketList.Destroy();
    begin
      Clear();
     
      inherited Destroy();
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstancePacketList.Clear();
    var
      List: TList;
      I: Integer;
    begin
      List := LockList();
      try
        for I := 0 to List.Count - 1 do
          Dispose(PShaiTrollInterOpCommunicationInterCOMInstancePacket(List.Items[I]));
     
        List.Clear();
      finally
        UnlockList();
      end;
    end;
     
     
    { TShaiTrollInterOpCommunicationInterCOMInstanceDispatcher }
     
    {* ----------------------------------------------------------------------------}
    constructor TShaiTrollInterOpCommunicationInterCOMInstanceDispatcher.Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager);
    begin
      inherited Create(True);
     
      FManager := AManager;
     
      Resume();
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceDispatcher.Execute();
    var
      Dummy: Pointer;
      More: Boolean;
    begin
      while not Terminated do
      begin
        try
          if not Manager.DispatchPacket(Dummy, @More) then
            if Assigned(Dummy) then
              Dispose(PShaiTrollInterOpCommunicationInterCOMInstancePacket(Dummy));
     
          if More then
            Sleep(0)
          else
            Sleep(10);
        except
          on E: Exception do
            ProtectThreadErrors(Format('Exception %s : "%s" during "Dispatcher"', [E.ClassName, E.Message]));
        end;
      end;
    end;
     
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceDispatcher.ProtectThreadErrors(const Context: string);
    begin
      Manager.WriteLog('ERROR_THREAD_DISPATCHER', ltException, 'Thread Error', Context);
    end;
     
    { TShaiTrollInterOpCommunicationInterCOMInstanceSender }
     
    {* ----------------------------------------------------------------------------}
    constructor TShaiTrollInterOpCommunicationInterCOMInstanceSender.Create(AManager: TShaiTrollInterOpCommunicationInterCOMInstanceManager);
    begin
      inherited Create(True);
     
      FManager := AManager;
     
      Resume();
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceSender.Execute;
    var
      P: Pointer;
      Packet: PShaiTrollInterOpCommunicationInterCOMInstancePacket absolute P;
      Canal: TShaiTrollInterOpCommunicationInterCOMInstanceCanal;
      More: Boolean;
      StepMark: string;
    begin
      while not Terminated do
      begin
        try
          StepMark := 'Pick';
          if Manager.PickPacketToSend(P, More) then
          begin
            StepMark := 'IsBadReadPtr Pick';
            if not IsBadReadPtr(Packet, SizeOf(Packet^)) then
            begin
              try
                StepMark := 'FindReceiver';
                if Packet.Header.ReceiverID = 0 then
                  Canal := Manager.Server
                else
                  Canal := Manager.FindClient(Packet.Header.ReceiverID);
     
                if Assigned(Canal) then
                begin
                  StepMark := 'SendPacket';
                  if not Canal.SendPacket(Packet) then
                  begin
                    Inc(Packet.Header.SendTentative);
                    Manager.WriteLog('ERROR_SENDER', ltError, Format('Packet Not Send to %s', [Canal.BuildId('Sender')]), Format('Tentative %d / 5', [Packet.Header.SendTentative]));
     
                    StepMark := 'ReSend';
                    if Packet.Header.SendTentative < 5 then
                    begin
                      Manager.AddPacketToSend(Packet); // On Retente !
                      Packet := nil;
                      More := True;
                    end;
                  end;
                end
                else
                  Manager.WriteLog('ERROR_SENDER', ltWarning, 'Canal Not Found', IntToStr(Packet.Header.ReceiverID));
              finally
                if Assigned(Packet) then
                begin
                  StepMark := 'IsBadWritePtr DisposePacket';
                  if not IsBadWritePtr(Packet, SizeOf(Packet^)) then
                  begin
                    StepMark := 'DisposePacket';
                    Dispose(Packet);
                  end
                  else
                    Manager.WriteLog('ERROR_SENDER', ltWarning, 'DisposePacket Is Bad Write Packet Pointer', IntToStr(Packet.Header.ReceiverID))
                end;
              end;
            end
            else
              Manager.WriteLog('ERROR_SENDER', ltWarning, 'PickPacketToSend Is Bad Read Packet Pointer');
          end;
     
          if More then
            Sleep(0)
          else
            Sleep(10);
        except
          on E: Exception do
            ProtectThreadErrors(Format('Exception %s : "%s" during "Sender.%s"', [E.ClassName, E.Message, StepMark]));
        end;
      end;
    end;
     
    {* ----------------------------------------------------------------------------}
    procedure TShaiTrollInterOpCommunicationInterCOMInstanceSender.ProtectThreadErrors(const Context: string);
    begin
      Manager.WriteLog('ERROR_THREAD_SENDER', ltException, 'Thread Error', Context);
    end;
     
    { EShaiTrollInterOpCommunicationInterCOMInstanceError }
     
    {* ----------------------------------------------------------------------------}
    constructor EShaiTrollInterOpCommunicationInterCOMInstanceError.Create(const Msg: string; ErrorCode: HRESULT);
    begin
      inherited Create(Message, ErrorCode, 0);
    end;
     
    {* ----------------------------------------------------------------------------}
    constructor EShaiTrollInterOpCommunicationInterCOMInstanceError.CreateFmt(const Msg: string; const Args: array of const; ErrorCode: HRESULT);
    begin
      inherited Create(Format(Msg, Args), ErrorCode, 0);
    end;
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
    end.


    sinon pour être propre

    je commencerais juste une protection du double 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
    Function TFMyForm.Arret: Boolean;
    begin
      if FichierEchange <> 0 then
      begin
        if Partage <> nil then
        begin
          UnmapViewOfFile(Partage);
          Partage := nil;
        end;
     
        CloseHandle(FichierEchange);
        FichierEchange  := 0;
      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

  7. #7
    Rédacteur/Modérateur

    Avatar de SergioMaster
    Homme Profil pro
    Développeur informatique retraité
    Inscrit en
    Janvier 2007
    Messages
    15 042
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 67
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur informatique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Janvier 2007
    Messages : 15 042
    Points : 40 955
    Points
    40 955
    Billets dans le blog
    62
    Par défaut
    Citation Envoyé par BuzzLeclaire Voir le message
    (je ne sais pas si je peut changer le titre de la discussion ?)
    Toi je ne sais pas, mais moi oui
    Cela te va comme nouveau titre ?
    MVP Embarcadero
    Delphi installés : D3,D7,D2010,XE4,XE7,D10 (Rio, Sidney), D11 (Alexandria), D12 (Athènes)
    SGBD : Firebird 2.5, 3, SQLite
    générateurs États : FastReport, Rave, QuickReport
    OS : Window Vista, Windows 10, Windows 11, Ubuntu, Androïd

  8. #8
    Membre éprouvé Avatar de BuzzLeclaire
    Homme Profil pro
    Dev/For/Vte/Ass
    Inscrit en
    Août 2008
    Messages
    1 606
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Dev/For/Vte/Ass

    Informations forums :
    Inscription : Août 2008
    Messages : 1 606
    Points : 1 113
    Points
    1 113
    Par défaut
    Citation Envoyé par ShaiLeTroll Voir le message
    Les violations d'accès c'est parfois retord et pas là où l'on croit, je commencerais juste une protection du double 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
    Function TFMyForm.Arret: Boolean;
    begin
      if FichierEchange <> 0 then
      begin
        if Partage <> nil then
        begin
          UnmapViewOfFile(Partage);
          Partage := nil;
        end;
     
        CloseHandle(FichierEchange);
        FichierEchange  := 0;
      end;
    End;
    En fait, pourquoi envoyer Données par PostMessage alors que vous avez Partage ?
    Ok
    Je m'exerce au Hook de souris, je suis d'accord avec Postmessage mais cela m'obligerai d'utiliser un TTimer ?

    D'ailleurs, en inhibant le PostMessage je n'ai plus de VA
    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
     
        FichierEchange := OpenFileMapping(FILE_MAP_WRITE,False,'ApplicationCible');
        if FichierEchange <> 0 then
        begin
          Partage := MapViewOfFile(FichierEchange,FILE_MAP_WRITE,0,0,0);
          if Partage <> nil then
          begin
            Souris := Pointer(Donnees);
     
            Partage^.Fenetre    := Souris^.hwnd;
            Partage^.SourisPosx := Souris^.Pt.x;
            Partage^.SourisPosy := Souris^.Pt.y;
     
            //
            //PostMessage(Partage^.HandleApplicationCible, WM_USER+0913, MsgID, Donnees);
            //
     
            UnmapViewOfFile(Partage);
          end;
          CloseHandle(FichierEchange);
        end;

    Citation Envoyé par Andnotor Voir le message
    UnmapViewOfFile ne va pas générer de VA, juste retourner FALSE en cas d'erreur.

    Mais une chose est sûr tu écris au-delà du fichier, le fichier mappé ne faisant que 4 octets (SizeOf(Partage) = taille d'un pointeur).
    Ok effectivement c'est 4 octets..., j'ai mi dwMaximumSizeLow à 0 qui fixe donc la valeur sur hfile mais cela ne change rien

    Pour info, je déclare Partage comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    type
      TPartage = record
        HandleApplicationCible,
        wHitTestCode,
        SourisPosx,SourisPosy,
        Fenetre : hwnd;
    end;
    PPartage = ^TPartage;

  9. #9
    Membre éprouvé Avatar de BuzzLeclaire
    Homme Profil pro
    Dev/For/Vte/Ass
    Inscrit en
    Août 2008
    Messages
    1 606
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Dev/For/Vte/Ass

    Informations forums :
    Inscription : Août 2008
    Messages : 1 606
    Points : 1 113
    Points
    1 113
    Par défaut
    Citation Envoyé par SergioMaster Voir le message
    Toi je ne sais pas, mais moi oui
    Cela te va comme nouveau titre ?
    Coucou Sergio

    Merci

  10. #10
    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 BuzzLeclaire Voir le message
    Je m'exerce au Hook de souris, je suis d'accord avec Postmessage mais cela m'obligerai d'utiliser un TTimer ?
    Je ne vois pas le rapport, que vient faire un TTimer dans l'échange de message ?

    Sinon, j'avais modifié mon message, j'ai fourni un code et je pense que tu dois mieux définir les taille de buffer (cf SHARED_MEMORY_SIZE dans mon code) et les notifications inter-processus
    Même si je pense que WM_COPYDATA pour échanger 20 octets me semble bien plus simple
    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

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

    Informations forums :
    Inscription : Septembre 2008
    Messages : 5 693
    Points : 13 128
    Points
    13 128
    Par défaut
    Citation Envoyé par BuzzLeclaire Voir le message
    Ok effectivement c'est 4 octets..., j'ai mi dwMaximumSizeLow à 0 qui fixe donc la valeur sur hfile mais cela ne change rien
    Il faut fixer la taille s'il n'y a pas de fichier disque (INVALID_HANDLE_VALUE) : SizeOf(TPartage).

  12. #12
    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
    bon alors je ne sais pas ce que tu cherches à faire mais ça m'a l'air un peu compliqué...

    pour échanger des données entre deux applications tu peux

    1) enregistrer un message dédié
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     MonMessage := RegisterWindowMessage('MonMessage super spécial');
    2) sur un TApplicationEvents.OnMessage tu testes cette valeur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    procedure TfrmMainWindow.ApplicationEvents1Message(var Msg: tagMSG;
      var Handled: Boolean);
    begin
      if Msg.message = MonMessage then
      begin
         ...
      end;
    end;
    j'utilise cela pour que différentes applications se détectent automatiquement
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
      PostMessage(HWND_BROADCAST, MonMessage, Handle, IdApplication);
    où Handle est le Handle d'une fenêtre de communication, et IdApplication permet de savoir quelle application je suis.

    donc l'application A démarre et Broadcast MonMessage ce qui ne sert à rien
    l'application B démarre et Broadcast MonMessage ce qui permet à A de savoir que B a été lancé
    l'application C démarre et Broadcast MonMEssage qui qui permet à A et B de savoir que C a été lancé...


    Ensuite je peux faire des échanges par WM_COPYDATA car chaque application possède des Handle target pour envoyer des messages

    pour envoyer un message j'utilise
    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
     
    type
        TSendString = record
          dwData : NativeInt;
          cbData : DWORD;
          lpData : string;
        end;
    var
      MSg: TSendString;
    begin
        Msg.dwData := Tag; // identifiant du message
        Msg.cbData := Length(Str) * SizeOf(Char);
        Msg.lpData := Str;
        Result := SendMessage(Target, WM_COPYDATA, Handle, LPARAM(@Msg));
    end;
    lpData est supposé être un simple pointer, j'utilise un String qui contient du JSON en l'occurrence

    et pour la réception

    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
     
      TWMCopyDataStringData = record
        Tag : NativeInt;
        Len : DWORD;
        Str : PChar;
      end;
     
      TWMCopyDataReceiveString = record
        Msg      : Cardinal;
        MsgFiller: TDWordFiller;
        From     : HWND;
        CopyData : ^TWMCopyDataStringData;
        Result   : LRESULT;
        function GetString: string;
      end;
     
    function TWMCopyDataReceiveString.GetString: string;
    begin
      SetString(Result, CopyData.Str, CopyData.Len div SizeOf(Char));
    end;
     
    type
      TForm1 ...
     
        procedure WMCopyData(var Msg: TWMCopyDataReceiveString); message WM_COPYDATA;
     
      end;
    avec JSON ça me permet d'envoyer ce que je veux, mais si tu as une structure fixe tu peux aussi l'utiliser; WM_COPYDATA demande deux paramètres, la taille des données et leur contenu, la seule limite c'est que la structure ne doit contenir aucun pointer (ou type dynamique).
    Developpez.com: Mes articles, forum FlashPascal
    Entreprise: Execute SARL
    Le Store Excute Store

  13. #13
    Membre éprouvé Avatar de BuzzLeclaire
    Homme Profil pro
    Dev/For/Vte/Ass
    Inscrit en
    Août 2008
    Messages
    1 606
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Dev/For/Vte/Ass

    Informations forums :
    Inscription : Août 2008
    Messages : 1 606
    Points : 1 113
    Points
    1 113
    Par défaut
    Citation Envoyé par Paul TOTH Voir le message
    bon alors je ne sais pas ce que tu cherches à faire mais ça m'a l'air un peu compliqué...
    Je m'exerce sur le HookMouse via DLL (aussi un hook clavier sans DLL mais là ça fonctionne sans souci)
    Merci pour tes informations.

    Citation Envoyé par Andnotor Voir le message
    Il faut fixer la taille s'il n'y a pas de fichier disque (INVALID_HANDLE_VALUE) : SizeOf(TPartage).


    Citation Envoyé par ShaiLeTroll Voir le message
    Je ne vois pas le rapport, que vient faire un TTimer dans l'échange de message ?

    Sinon, j'avais modifié mon message, j'ai fourni un code et je pense que tu dois mieux définir les taille de buffer (cf SHARED_MEMORY_SIZE dans mon code) et les notifications inter-processus
    Même si je pense que WM_COPYDATA pour échanger 20 octets me semble bien plus simple
    @Shail,
    Si je retire PostMessage, comment je peux lire le fichier mapé lorsque la souris bouge ? Je ne comprends pas ! Si mon appli est invisible ou n'est pas active je ne peux pas utiliser non plus le OnMouseMove pour lire les informations envoyées par ma DLL.


    @Merci pour toutes vos informations, j'ai de la lecture hihihihihi

  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
    Même avis que Paul Toth, un message pour récupérer HandleApplicationCible puis un message en retour la donnée via WM_COPYDATA, cela sera plus simple

    Sinon

    Citation Envoyé par BuzzLeclaire Voir le message
    @Shail,
    Si je retire PostMessage, comment je peux lire le fichier mapé lorsque la souris bouge ? Je ne comprends pas ! Si mon appli est invisible ou n'est pas active je ne peux pas utiliser non plus le OnMouseMove pour lire les informations envoyées par ma DLL.
    Euh Pourquoi Shail ? c'est soit juste Shai ou Shai Le Troll !

    Sinon, je n'ai jamais dit de retirer PostMessage
    Citation Envoyé par ShaiLeTroll Voir le message
    En fait, pourquoi envoyer Donnees par PostMessage alors que vous avez Partage ?
    ce qui me choque c'est le paramètre Donnees en LPARAM de PostMessage
    La notification me parait tout à fait normal, le MsgID pourquoi pas même si je l'aurais mis en donnée aussi mais Donnees n'a pas à être transmis

    Votre code

    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
     
        FichierEchange := OpenFileMapping(FILE_MAP_WRITE,False,'ApplicationCible');
        if FichierEchange <> 0 then
        begin
          Partage := PPartage(MapViewOfFile(FichierEchange,FILE_MAP_WRITE,0,0,0));
          if Partage <> nil then
          begin
            Souris := Pointer(Donnees);
     
            Partage^.Fenetre    := Souris^.hwnd;
            Partage^.SourisPosx := Souris^.Pt.x;
            Partage^.SourisPosy := Souris^.Pt.y;
     
            PostMessage(Partage^.HandleApplicationCible, WM_USER+0913, MsgID, Donnees); // je mettrais 0 à la place de Donnees
     
            UnmapViewOfFile(Partage);
          end;
          CloseHandle(FichierEchange);
        end;
    ce qui me choque

    d'où sort HandleApplicationCible ?
    il est pré-rempli par l'application Cible avant que vous fassiez OpenFileMapping ?
    j'ai toujours utilisé CreateFileMapping n'étant pas certains qui serait le premier à ouvrir le partage et donc je l'ai toujours supposé vide car c'est via un CreateEvent (remplace le PostMessage) qui gérait le signal d'un dépôt de données.


    pour ma part, j'insiste sur le fait que la taille doit être défini

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Partage := PPartage(MapViewOfFile(FichierEchange,FILE_MAP_WRITE,0,0,SizeOf(TPartage)));
    et dans le programme qui fait le CreateFileMapping, j'espère que c'est fait ainsi

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    FichierEchange := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0, SizeOf(TPartage), 'ApplicationCible');
    Partage := PPartage(MapViewOfFile(FichierEchange, FILE_MAP_READ, 0, 0,  SizeOf(TPartage)));


    Enfin, tout ça semble la suite de Hook dans TService

    Vous avez scindé tout ça en deux ?
    Un Exe sur le bureau qui installe la DLL de Hook (TLowLevelMouseHook)
    Une solution avec un simple CallBack entre DLL et EXE n'aurait-il pas été simple ?

    Ensuite comme tout cela sera interfacé avec le TService ?
    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
    Membre éprouvé Avatar de BuzzLeclaire
    Homme Profil pro
    Dev/For/Vte/Ass
    Inscrit en
    Août 2008
    Messages
    1 606
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Dev/For/Vte/Ass

    Informations forums :
    Inscription : Août 2008
    Messages : 1 606
    Points : 1 113
    Points
    1 113
    Par défaut
    Citation Envoyé par ShaiLeTroll Voir le message
    Euh Pourquoi Shail ? c'est soit juste Shai ou Shai Le Troll !
    Oups je crois l'écrire comme ça depuis le début...
    Je ferais attention... 8

    Citation Envoyé par ShaiLeTroll Voir le message
    Sinon, je n'ai jamais dit de retirer PostMessage

    ce qui me choque c'est le paramètre Donnees en LPARAM de PostMessage
    La notification me parait tout à fait normal, le MsgID pourquoi pas même si je l'aurais mis en donnée aussi mais Donnees n'a pas à être transmis

    Citation Envoyé par ShaiLeTroll Voir le message
    d'où sort HandleApplicationCible ?
    il est pré-rempli par l'application Cible avant que vous fassiez OpenFileMapping ?
    ah ok... biensur... sinon il vient de là (il viens du blues )
    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
     
    type
      TDonneesRecu = record
        HookSouris: HHOOK;
        HandleApplicationCible: HWnd;
      end;
    var
      DonneesRecu: TDonneesRecu;
     
    procedure DebHookMouse(const HandleApp: HWnd); stdcall;
    begin
      if DonneesRecu.HookSouris = 0 then
      begin
        DonneesRecu.HookSouris:=SetWindowsHookEx(WH_MOUSE,@HookProcedure, HInstance,0);
        DonneesRecu.HandleApplicationCible := HandleApp;
      end;
    end;
    Citation Envoyé par ShaiLeTroll Voir le message
    j'ai toujours utilisé CreateFileMapping n'étant pas certains qui serait le premier à ouvrir le partage et donc je l'ai toujours supposé vide car c'est via un CreateEvent (remplace le PostMessage) qui gérait le signal d'un dépôt de données.

    pour ma part, j'insiste sur le fait que la taille doit être défini
    Ok

    Merci Shai

  16. #16
    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
    Si tu as fait ta propre DLL pour avec la fonction DebHookMouse pourquoi ne pas passer un CallBack au lieu de passer le Handle ?
    Ainsi la DLL appelle le CallBack directement lorsqu'elle a des coordonnées
    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

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

    Informations forums :
    Inscription : Septembre 2008
    Messages : 5 693
    Points : 13 128
    Points
    13 128
    Par défaut
    WM_COPYDATA par SendMessage sur un hook souris ? Je dis pas vraiment vu le nombre de messages (synchrones) qui seront générés

    A noter que ce hook est injectée dans chaque processus mais DonneesRecu.HandleApplicationCible ne sera valide que dans le processus qui a effectivement chargé la DLL, il vaudra toujours 0 dans les autres.

    Si tu veux rester sur un fichier mappé, il faudrait aussi appeler une seule fois OpenFileMapping/MapViewOfFile au chargement de la DLL, pas sur chaque message et renseigner HandleApplicationCible depuis l'exe après CreateFileMapping.

    Enfin si tu veux uniquement récupérer Handle et Pt, tu peux simplement passer par

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    Wnd := FindWindow(...);
    PostMessage(Wnd, MonMessageOnMove, Handle, MAKELPARAM(Pt.X, Pt.Y));

  18. #18
    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
    Sinon pour le MAKELPARAM, tout à fait on trouve cela dans pas mal de message, moi je l'ai utilisé qu'avec EM_CHARFROMPOS
    Si l'on stocke les données dans un TPoint, pour question de lisibilité la fonction PointToLParam fait le même boulot

    Tu peux aussi utiliser TSmallPoint et SmallPointToPoint/PointToSmallPoint cependant une variable TSmallPoint est compatible avec LPARAM uniquement en 32Bits
    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

Discussions similaires

  1. .my_kshrc[25]: no closing quote
    Par esipage dans le forum Shell et commandes GNU
    Réponses: 1
    Dernier message: 04/09/2012, 12h28
  2. String literal is not properly closed by a double-quote
    Par soufiane10 dans le forum Servlets/JSP
    Réponses: 5
    Dernier message: 24/03/2009, 23h22

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