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

Composants VCL Delphi Discussion :

Comment utiliser TTimer pour détecter un événement dans un répertoire ?


Sujet :

Composants VCL Delphi

  1. #1
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2003
    Messages
    803
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2003
    Messages : 803
    Points : 182
    Points
    182
    Par défaut Comment utiliser TTimer pour détecter un événement dans un répertoire ?
    Bonjour,

    Quelqu'un voit-il comment utiliser TTimer pour détecter l'introduction d'un nouveau fichier dans un répertoire ?

  2. #2
    Membre actif
    Profil pro
    Inscrit en
    Juillet 2003
    Messages
    190
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2003
    Messages : 190
    Points : 218
    Points
    218
    Par défaut
    bonjour

    tu fais la liste des fichiers a l'instant T

    sur l'evt timer tu refais une nouvelle liste et tu la compare par rapport a l'ancienne liste si modification tu fais ton traitement et tu met a jour ta liste

    le timer sert juste a declencher la procedure de verification du contenu du repertoire a interval régulier

  3. #3
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 560
    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 560
    Points : 25 156
    Points
    25 156
    Par défaut
    Pourquoi pas un Thread et FindFirstChangeNotification, c'est prévu pour !
    Tient, c'est un peu brut, c'est un code que j'ai dans un de mes programmes ...

    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
    type
      TFileSizeList = class(TStringList)
      private
        FCritical: TCriticalSection;
        function GetSize(const FileName: string): Integer;
        procedure SetSize(const FileName: string; const Value: Integer);
        function GetOldSize(const FileName: string): Integer;
        function GetSizes(const Index: Integer): TFileSizeListItem;
        function GetLastMessage(const Index: Integer): string;
        procedure SetLastMessage(const Index: Integer; const Value: string);
      public
        constructor Create();
        destructor Destroy(); override;
        procedure Clear(); override;
        function GetMessages(): string;
        property Size[const FileName: string]: Integer read GetSize write SetSize;
        property OldSize[const FileName: string]: Integer read GetOldSize;
        property Sizes[const Index: Integer]: TFileSizeListItem read GetSizes;
        property LastMessage[const Index: Integer]: string read GetLastMessage write SetLastMessage;
      end;
     
      TNotifyShaiFileChangeThread = class(TThread)
      private
         FDirName: string;
         FOnChange: TFileMessageEvent;
         FOnIdle: TFileMessageEvent;
         FFlash: Boolean;
         FFlashCritical: TCriticalSection;
         FFileSize: TFileSizeList;
         FExcludeFile: TStringList;
         procedure DoChange();
         procedure DoIdle();
         procedure ReadLastMessages();
      protected
         function GetFlash(): Boolean;
         procedure SetFlash(Value: Boolean);
      public
         constructor Create(const DirName: string; const AExcludeFile: TStrings; AOnChange, AOnIdle: TFileMessageEvent);
         destructor Destroy(); override;
         procedure Execute; override;
         class procedure ChangeFlash(Active: Boolean);
     
         property OnChange: TFileMessageEvent read FOnChange write FOnChange;
         property OnIdle: TFileMessageEvent read FOnIdle write FOnIdle;
         property Flash: Boolean read GetFlash write SetFlash;
      end;
    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
    { TNotifyShaiFileChangeThread}
     
    constructor TNotifyShaiFileChangeThread.Create(const DirName: string; const AExcludeFile: TStrings; AOnChange, AOnIdle: TFileMessageEvent);
    var
       I: Integer;
    begin
       inherited Create(True);
     
       FFlashCritical := TCriticalSection.Create();
       FreeOnTerminate := True;
       FDirName := IncludeTrailingPathDelimiter(DirName);
       FOnChange := AOnChange;
       FOnIdle := AOnIdle;
       FFileSize := TFileSizeList.Create();
     
       FExcludeFile := TStringList.Create();
       FExcludeFile.Sorted := True;
       FExcludeFile.Duplicates := dupIgnore;
       FExcludeFile.CaseSensitive := False;
       if Assigned(AExcludeFile) then
          for I := 0 to AExcludeFile.Count - 1 do
            FExcludeFile.Add(AExcludeFile.Values[AExcludeFile.Names[I]]);
     
       Resume();
    end;
     
    destructor TNotifyShaiFileChangeThread.Destroy();
    begin
       if Assigned(FExcludeFile) then
       begin
          FExcludeFile.Free();
          FExcludeFile := nil;
       end;
     
       if Assigned(FFileSize) then
       begin
          FFileSize.Free();
          FFileSize := nil;
       end;
     
       if Assigned(FFlashCritical) then
       begin
          FFlashCritical.Free();
          FFlashCritical := nil;
       end;
    end;
     
    function TNotifyShaiFileChangeThread.GetFlash(): Boolean;
    begin
       FFlashCritical.Acquire();
       try
          Result := FFlash;
          FFlash := False;
       finally
          FFlashCritical.Release();
       end;
    end;
     
    procedure TNotifyShaiFileChangeThread.SetFlash(Value: Boolean);
    begin
       FFlashCritical.Acquire();
       try
          FFlash := Value;
       finally
          FFlashCritical.Release();
       end;
    end;
     
    class procedure TNotifyShaiFileChangeThread.ChangeFlash(Active: Boolean);
    begin
       _InternalThread.Flash := Active;
    end;
     
    procedure TNotifyShaiFileChangeThread.Execute();
    var
       HandleNotification: THandle;
       Delay: Cardinal;
    begin
       ReadLastMessages;
     
       Delay := 1000;
       Sleep(Delay);
     
       HandleNotification := FindFirstChangeNotification(PChar(FDirName), True, FILE_NOTIFY_CHANGE_SIZE);
       try
          while not Terminated do
          begin
             case WaitForSingleObject(HandleNotification, Delay) of
                WAIT_OBJECT_0 :
                   begin
                     ReadLastMessages;
                     Synchronize(DoChange);
                     Delay := 1000;
                     FindNextChangeNotification(HandleNotification);
                   end;
                WAIT_ABANDONED : Terminate;
                WAIT_TIMEOUT :
                   begin
                      Synchronize(DoIdle);
                      Delay := 200;
                   end;
             end;
          end;
       finally
          FindCloseChangeNotification(HandleNotification);
       end;
    end;
     
    procedure TNotifyShaiFileChangeThread.DoChange();
    begin
       try
          if Assigned(FOnChange) then
          begin
            FOnChange(Self, FFileSize.GetMessages());
          end;
       except
          Exit;
       end;
    end;
     
    procedure TNotifyShaiFileChangeThread.DoIdle();
    begin
       try
          if Assigned(FOnIdle) then
          begin
            FOnIdle(Self, FormatDateTime(' : dddd dd mmmm à hh:nn:ss', Now()));
          end;
       except
          Exit;
       end;
    end;
     
    {$WARN SYMBOL_PLATFORM OFF}
    procedure TNotifyShaiFileChangeThread.ReadLastMessages();
     
      procedure FillSizes();
      var
        SearchRec: TSearchRec;
        SearcMask: string;
      begin
        FFileSize.BeginUpdate();
        try
          SearcMask := '*.log';
          if FindFirst(FDirName+SearcMask, faAnyFile, SearchRec)= 0 then
          begin
            repeat
              if FExcludeFile.IndexOf(SearchRec.Name) < 0 then
                 FFileSize.Size[SearchRec.Name] := TWin32FindData(SearchRec.FindData).nFileSizeLow; // Peu probable que cela dépasse 2Go, je ne gère pas High
            until FindNext(SearchRec) <> 0;
          end;
        finally
          FFileSize.EndUpdate();
        end;
      end;
     
      function ReadLastMessage(const FileName: string; Index, Count: Integer): string;
      var
        F: File;
        OldFM: Byte;
        AmtTransferred: Integer;
      begin
        try
          AssignFile(F, FDirName+FileName);
          OldFM := FileMode;
          FileMode := 0;
          try
            Reset(F, 1);
            try
              Seek(F, Index);
              SetLength(Result, Count);
              BlockRead(F, Result[1], Count, AmtTransferred);
              SetLength(Result, AmtTransferred);
            finally
              CloseFile(F);
            end;
          finally
            FileMode := OldFM;
          end;
        except
          on E: Exception do Result := E.Message;
        end;
      end;
     
      procedure CheckSizes();
      var
        ifs: Integer;
        Item: TFileSizeListItem;
      begin
        for ifs := 0 to FFileSize.Count - 1 do
        begin
          Item := FFileSize.Sizes[ifs];
          if Item.Size > Item.OldSize then
            FFileSize.LastMessage[ifs] := ReadLastMessage(FFileSize[ifs], Item.OldSize, Item.Size-Item.OldSize-1);
        end;
      end;
     
    begin
      try
        FillSizes();
        CheckSizes();
      except
        on E: Exception do Exit;
      end;
    end;
     
    { TFileSizeList }
     
    constructor TFileSizeList.Create();
    begin
      inherited Create();
     
      FCritical := TCriticalSection.Create();
      Sorted := True;
      Duplicates := dupIgnore;
    end;
     
     
    destructor TFileSizeList.Destroy();
    begin
      inherited Destroy();
     
      if Assigned(FCritical) then
      begin
        FCritical.Free();
        FCritical := nil;
      end;
    end;
     
    procedure TFileSizeList.Clear();
    var
      Index: Integer;
    begin
      FCritical.Acquire();
      try
        for Index := 0 to Count - 1 do
          if Assigned(Objects[Index]) then
            Dispose(PFileSizeListItem(Objects[Index]));
        inherited Clear();
      finally
        FCritical.Release();
      end;
    end;
     
    function TFileSizeList.GetSize(const FileName: string): Integer;
    var
      Index: Integer;
    begin
      Index := IndexOf(FileName);
      if Index >= 0 then
        Result := PFileSizeListItem(Objects[Index])^.Size
      else
        Result := -1;
    end;
     
    procedure TFileSizeList.SetSize(const FileName: string; const Value: Integer);
    var
      Index: Integer;
      Item: PFileSizeListItem;
    begin
      FCritical.Acquire();
      try
        Index := IndexOf(FileName);
        if Index >= 0 then
        begin
          PFileSizeListItem(Objects[Index])^.OldSize := PFileSizeListItem(Objects[Index])^.Size;
          PFileSizeListItem(Objects[Index])^.Size := Value;
          PFileSizeListItem(Objects[Index])^.LastMessage := '';
        end else
        begin
          New(Item);
          Item^.OldSize := Value;
          Item^.Size := Value;
          Item^.LastMessage := '';
          AddObject(FileName, Pointer(Item));
        end;
      finally
        FCritical.Release();
      end;
    end;
     
    function TFileSizeList.GetOldSize(const FileName: string): Integer;
    var
      Index: Integer;
    begin
      Index := IndexOf(FileName);
      if Index >= 0 then
        Result := PFileSizeListItem(Objects[Index])^.OldSize
      else
        Result := -1;
    end;
     
    function TFileSizeList.GetSizes(const Index: Integer): TFileSizeListItem;
    begin
      Result := PFileSizeListItem(Objects[Index])^;
    end;
     
    function TFileSizeList.GetLastMessage(const Index: Integer): string;
    begin
      FCritical.Acquire();
      try
        if Index < Count then
          Result := PFileSizeListItem(Objects[Index])^.LastMessage
        else
          Result := '';
      finally
        FCritical.Release();
      end;
    end;
     
    procedure TFileSizeList.SetLastMessage(const Index: Integer; const Value: string);
    begin
      FCritical.Acquire();
      try
        if Index < Count then
          PFileSizeListItem(Objects[Index])^.LastMessage := Value;
      finally
        FCritical.Release();
      end;
    end;
     
    function TFileSizeList.GetMessages: string;
    var
      Index: Integer;
      Msg: WideString;
    begin
      Result := '';
      for Index := 0 to Count - 1 do
      begin
        Msg := LastMessage[Index];
        if Length(Msg) > 0 then
        begin
          Msg := StringReplace(Msg, ' <', ' ', [rfReplaceAll]);
          Msg := StringReplace(Msg, '>'#9, ' : <B>', [rfReplaceAll]);
          Msg := StringReplace(Msg, #13, '</B><BR>', [rfReplaceAll]);
          Result := Result + '<BR>' + Msg;
        end;
      end;
      Result := StringReplace(Utf8ToAnsi(Result), #13, ' ', [rfReplaceAll]);
    end;

  4. #4
    Membre habitué
    Profil pro
    Inscrit en
    Juillet 2003
    Messages
    803
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2003
    Messages : 803
    Points : 182
    Points
    182
    Par défaut OK j'ai résolu le problème avec un thread
    Bonjour,

    Effectivement la solution se trouvait être dans l'utilisation d'un thread et ça marche !

    Merci à tous

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

Discussions similaires

  1. Réponses: 2
    Dernier message: 17/04/2012, 12h04
  2. [JAXB] Comment utiliser JAXB pour le mapping des classes définies dans mon XSD ?
    Par yassirjanati dans le forum Format d'échange (XML, JSON...)
    Réponses: 1
    Dernier message: 13/10/2011, 13h54
  3. Réponses: 14
    Dernier message: 10/07/2008, 11h56
  4. [Virtual Pascal] Comment utiliser linker pour que run fonctionne dans le compilateur
    Par gmaxjeu dans le forum Autres IDE
    Réponses: 1
    Dernier message: 04/07/2008, 20h44
  5. Réponses: 2
    Dernier message: 27/04/2006, 16h45

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