Ajuda para passar de C# para o Delphi

Delphi

25/04/2005

Olá amigos

Tenho um sistema que monitora pastas. Quando abri o site hoje vi um artigo que faz a mesma coisa, porém em .net. Só que o código está em C e eu não sei nada de C. Alguem pode me ajudar com este trecho? o restante do código consegui fazer...

public Form1()
{
      InitializeComponent();

      // CHAMA FUNÇÃO DE MONITORAMENTO
      Monitora();
}

public void Monitora()
{
      Try
      {
            //FILTRANDO PELO NOME
            oMonitor.NotifyFilter = NotifyFilters.FileName;

            //OUTRAS VERIFICAÇÕES POSSÍVEIS
            //NotifyFilters.LastAccess
            //NotifyFilters.LastWrite
            //NotifyFilters.FileName
            //NotifyFilters.DirectoryName;

            //EVENTO CHAMADO AO CÓPIAR NA PASTA
            oMonitor.Created += new FileSystemEventHandler(OnChanged);

      }
      catch
      {
            MessageBox.Show("Ocorreu um erro, verifique o caminho da                   pasta monitorada!");
            this.lblAviso.Text = "";
      }

}

//EVENTO CHAMADO APÓS COPIAR O ARQUIVO
private void OnChanged(object source, FileSystemEventArgs e)
{
      cont++;
      this.txtMensagem.Text = "Arquivos monitorados: " +             cont.ToString();
      this.listArquivo.Items.Add(e.Name.ToString());
}



Obrigado

Sanses


Sanses

Sanses

Curtidas 0

Respostas

Rjun

Rjun

25/04/2005

Bom :

o bloco Try...catch no delphi você usaria Try...except

no trecho oMonitor.Created += new FileSystemEventHandler(OnChanged);

você esta adicionando desviando o evento Created do objeto oMonitor para a função OnChanged.


GOSTEI 0
Massuda

Massuda

25/04/2005

Sem saber o que é oMonitor fica difícil fazer a conversão, mas segue alguns pontos importantes:[list:b438774e90][*:b438774e90]C usa a função InitializeComponent() para criar dinamicamente todos os componentes contidos no form; em Delphi (ao menos para Win32) normalmente isso não é preciso porque os componentes são criados através do arquivo DFM.[*:b438774e90]oMonitor.NotifyFilter é uma propriedade que recebe um dos valores possíveis da enumeração NotifyFilters.[*:b438774e90]A linha
oMonitor.Created += new FileSystemEventHandler(OnChanged);
equivale a fazer
oMonitor.Created := OnChanged;
Assumindo que OnChanged seja um procedure do tipo esperado pelo evento Created.[*:b438774e90]Em C [b:b438774e90]this[/b:b438774e90] tem o mesmo significado de [b:b438774e90]Self[/b:b438774e90] em Delphi.[/list:u:b438774e90]


GOSTEI 0
Sanses

Sanses

25/04/2005

olá

o link da matéria é este
[url]http://www.neoficio.com.br/msdn/colunistas/Schmitt/03_monitorando_pastas.asp[url]

mesmo com a ajuda de voces ainda não consegui, vou ter que estudar C, rss.

Obrigado

Sanses[/url]


GOSTEI 0
Sanses

Sanses

25/04/2005

nossa, msg cheia de erros...
o link

[url]http://www.neoficio.com.br/msdn/colunistas/Schmitt/03_monitorando_pastas.asp[/url]

Sanses


GOSTEI 0
Massuda

Massuda

25/04/2005

Não seria mais simples fazer isso em Delphi? Me parece que existe um componente que faz isso que vem junto com o Delphi a partir da versão 6 (não lembro o nome, mas parece que está na aba Samples).


GOSTEI 0
Rjun

Rjun

25/04/2005

Me parece que existe um componente que faz isso que vem junto com o Delphi a partir da versão 6


[b:562b8313a6]ShellChangeNotifier[/b:562b8313a6] na aba Samples


GOSTEI 0
Sanses

Sanses

25/04/2005

mas não serve para o .net

mesmo assim obrigado

Sanses


GOSTEI 0
Sanses

Sanses

25/04/2005

e a propósito, estou tentando fazer no delphi mesmo, como o proprio título da mensagem diz, passar de C para Delphi

Sanses


GOSTEI 0
Rjun

Rjun

25/04/2005

D8 ou D2005 ?


GOSTEI 0
Sanses

Sanses

25/04/2005

D 2005 e o caso é que minha aplicaçãojá etá em pascal,nãohá comou utiliza o C.

Sanses


GOSTEI 0
Sanses

Sanses

25/04/2005

UP :)


GOSTEI 0
Nerdex

Nerdex

25/04/2005

Em vez de usar a ShellChangeNotifier da aba Samples...
Pode usara API Hoock, que funciona com .NET...

Nosso colega Nildo é perito nesse assunto...
Tem um site para baixar isto: MadHoock (dá uma pesquisada antes aqui);


GOSTEI 0
Sanses

Sanses

25/04/2005

Concordo que é uma saída Nerdex, mais veja, estou migrando meu programa para o .NET. Tenho tempo para fazer, e vou aproveitar este tempo para aprender a trabalhar com as classes que o framework oferece, mesmo por que, quando essa plataforma estiver sendo amplamente utilizada, e se tivermos conhecimento das técnicas aplicadas, não precisaremos de componentes de terceiros para realizar tarefas que são nativas dos respectivos namespaces. Por isso volto a perguntr, alguem conseguiu resolver este problema? Sim, porque todos os exemplos( a maioria ) que encontrarmos, fatalmente será em C ou VB.

Obrigado pela Atenção
Mas continua sem solução

Sanses


GOSTEI 0
Massuda

Massuda

25/04/2005

Eu não trabalho com Delphi para .Net, mas tenho algum conhecimento de C.

Acho que o primeiro passo seria você criar uam instância do monitor via Delphi. A classe FileSystemWatcher é definida no namespace System.IO do framework. Com certeza os colegas que usam D8 ou D2005 podem te ajudar neste ponto.

Feito isso, você deve ajustar a propriedade NotifyFilter e atribuir um tratador de evento ao evento Created.


GOSTEI 0
Sanses

Sanses

25/04/2005

Olá

Meu problema está aqui:
procedure monitora();
begin
  try
   //FILTRANDO PELO NOME
   oMonitor.NotifyFilter := NotifyFilters.FileName;
   //OUTRAS VERIFICAÇÕES POSSÍVEIS, //NotifyFilters.LastAccess
   //NotifyFilters.LastWrite, //NotifyFilters.FileName, //NotifyFilters.DirectoryName;
   //EVENTO CHAMADO AO CÓPIAR NA PASTA
   oMonitor.Created := FileSystemEventHandler(Changed);
   except
   MessageBox.Show(´Ocorreu um erro, verifique o caminho da pasta monitorada!´,´Aviso Monitor´);
   end;
end;


oMonitor.Created := FileSystemEventHandler(Changed); >>ERRO

Diz que Changerd não é reconhecido
e também ´:=´ read/qrite not allowed CLR

Sanses


GOSTEI 0
Massuda

Massuda

25/04/2005

Pelo pouco que vi do Delphi para .Net, seu código devia ser algo assim:
procedure TSeuForm.Monitorar;
begin
  try
    ...
    Include(oMonitor.Created, ...seu tratador do evento...);
    // achava que isto deveria funcionar
    // oMonitor.Created := ...seu tratador do evento...
  except
    ...
  end;
end;



GOSTEI 0
Sanses

Sanses

25/04/2005

Olá Massuda

Alterei o código como voce indicou

Include(oMonitor.created, FileSystemEventHandler.onchanged);

mas dá erro de Record, object or class type required

Ainda assim tem mais uma parte que não entendo onde se encaixa:
private void OnChanged(object source, FileSystemEventArgs e)
{
      cont++;
      this.txtMensagem.Text = "Arquivos monitorados: " +             cont.ToString();
      this.listArquivo.Items.Add(e.Name.ToString());
}


Obrigado pela ajuda
Sanses


GOSTEI 0
Massuda

Massuda

25/04/2005

Não tenho experiência com Delphi para .Net, mas me parece que o código seria algo assim:
uses
  System.IO,
  ...

type
  TSeuForm = class(...
  ....
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    FWatcher: System.IO.FileSystemWatcher;
    procedure FileChanged(Sender: System.Object; E: 
System.IO.FileSystemEventArgs);
  ....

procedure TSeuForm.FormCreate(Sender: TObject);
begin
  FWatcher := FileSystemWatcher.Create;

  // path do diretório a ser monitorado
  FWatcher.Path := ExtractFileParh(Application.ExeName);

  // especificação dos arquivos a serem monitorados
  FWatcher.Filter := ´*.txt´;

  // o que vai ser monitorado
  FWatcher.NotifyFilter := NotifyFilters.LastWrite;

  Include(FWatcher.Changed, FileChanged);

  FWatcher.EnableRaisingEvents := True;
   ....
end;

procedure TSeuForm.FormDestroy(Sender: TObject);
begin
  FWatcher.EnableRaisingEvents := False;
  FWatcher.Free;
  ...
end;

procedure TSeuForm.FileChanged(Sender: System.Object; E: 
System.IO.FileSystemEventArgs);
begin
  // E.ChangeType diz qual mudança ocorreu
  // E.FullPath é o caminho para o arquivo afetado
  // E.Name é o nome do arquivo afetado
end;

Para obter mais informações sobre a classe FileSystemWatcher, consulte [url=http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemIOFileSystemWatcherClassTopic.asp]este artigo[/url] do MSDN.


GOSTEI 0
Sanses

Sanses

25/04/2005

Massuda, obrigado pela ajuda. Fiz algumas alterações no seu código e agora funciona perfeitamente. Se quiser uma cópia dos fontes de um reply, que te envio.

De qualquer forma, sergue a baixo a unit completa para consultas posteriores:
unit umonitor;

interface

uses
  System.Drawing, System.Collections, System.ComponentModel,
  System.Windows.Forms, System.Data, System.IO;

type
  TWinForm2 = class(System.Windows.Forms.Form)
  {$REGION ´Designer Managed Code´}
  strict private
    /// <summary>
    /// Required designer variable.
    /// </summary>
    Components: System.ComponentModel.Container;
    Label1: System.Windows.Forms.Label;
    Label2: System.Windows.Forms.Label;
    Label3: System.Windows.Forms.Label;
    Label4: System.Windows.Forms.Label;
    listArquivo: System.Windows.Forms.ListBox;
    btiniciar: System.Windows.Forms.Button;
    btparar: System.Windows.Forms.Button;
    txtCaminho: System.Windows.Forms.TextBox;
    DropArquivos: System.Windows.Forms.ComboBox;
    txtmensagem: System.Windows.Forms.TextBox;
    Label5: System.Windows.Forms.Label;
    lblaviso: System.Windows.Forms.Label;
    Label6: System.Windows.Forms.Label;
    lbNomearquivo: System.Windows.Forms.Label;
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    procedure InitializeComponent;
    procedure btiniciar_Click(sender: System.Object; e: System.EventArgs);
    procedure Label6_Click(sender: System.Object; e: System.EventArgs);
    procedure btparar_Click(sender: System.Object; e: System.EventArgs);
    procedure TWinForm2_Load(sender: System.Object; e: System.EventArgs);
  {$ENDREGION}
  strict protected
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    procedure Dispose(Disposing: Boolean); override;
  private
    { Private Declarations }
    FWatcher: System.IO.FileSystemWatcher;
    cont : integer;
    procedure FileChanged(Sender: System.Object; E:System.IO.FileSystemEventArgs);
  public
    constructor Create;
  end;

  [assembly: RuntimeRequiredAttribute(TypeOf(TWinForm2))]

implementation

{$AUTOBOX ON}


{$REGION ´Windows Form Designer generated code´}
/// <summary>
/// Required method for Designer support -- do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure TWinForm2.InitializeComponent;
type
  TArrayOfSystem_Object = array of System.Object;
begin
  Self.Label1 := System.Windows.Forms.Label.Create;
  Self.Label2 := System.Windows.Forms.Label.Create;
  Self.Label3 := System.Windows.Forms.Label.Create;
  Self.Label4 := System.Windows.Forms.Label.Create;
  Self.btiniciar := System.Windows.Forms.Button.Create;
  Self.btparar := System.Windows.Forms.Button.Create;
  Self.txtCaminho := System.Windows.Forms.TextBox.Create;
  Self.DropArquivos := System.Windows.Forms.ComboBox.Create;
  Self.txtmensagem := System.Windows.Forms.TextBox.Create;
  Self.Label5 := System.Windows.Forms.Label.Create;
  Self.lblaviso := System.Windows.Forms.Label.Create;
  Self.listArquivo := System.Windows.Forms.ListBox.Create;
  Self.Label6 := System.Windows.Forms.Label.Create;
  Self.lbNomearquivo := System.Windows.Forms.Label.Create;
  Self.SuspendLayout;
  // 
  // Label1
  // 
  Self.Label1.Anchor := (System.Windows.Forms.AnchorStyles((((System.Windows.Forms.AnchorStyles.Top 
    or System.Windows.Forms.AnchorStyles.Bottom) or System.Windows.Forms.AnchorStyles.Left) 
    or System.Windows.Forms.AnchorStyles.Right)));
  Self.Label1.AutoSize := True;
  Self.Label1.Font := System.Drawing.Font.Create(´Tahoma´, 11.25, System.Drawing.FontStyle.Bold, 
      System.Drawing.GraphicsUnit.Point, (Byte(0)));
  Self.Label1.Location := System.Drawing.Point.Create(8, 16);
  Self.Label1.Name := ´Label1´;
  Self.Label1.Size := System.Drawing.Size.Create(224, 22);
  Self.Label1.TabIndex := 0;
  Self.Label1.Text := ´Software de Monitoramento´;
  // 
  // Label2
  // 
  Self.Label2.AutoSize := True;
  Self.Label2.Location := System.Drawing.Point.Create(8, 48);
  Self.Label2.Name := ´Label2´;
  Self.Label2.Size := System.Drawing.Size.Create(96, 17);
  Self.Label2.TabIndex := 1;
  Self.Label2.Text := ´Monitorar a Pasta:´;
  // 
  // Label3
  // 
  Self.Label3.AutoSize := True;
  Self.Label3.Location := System.Drawing.Point.Create(8, 108);
  Self.Label3.Name := ´Label3´;
  Self.Label3.Size := System.Drawing.Size.Create(102, 17);
  Self.Label3.TabIndex := 2;
  Self.Label3.Text := ´Monitorar Arquivos:´;
  // 
  // Label4
  // 
  Self.Label4.AutoSize := True;
  Self.Label4.Location := System.Drawing.Point.Create(8, 168);
  Self.Label4.Name := ´Label4´;
  Self.Label4.Size := System.Drawing.Size.Create(163, 17);
  Self.Label4.TabIndex := 3;
  Self.Label4.Text := ´Arquivos monitorados na pasta:´;
  // 
  // btiniciar
  // 
  Self.btiniciar.Location := System.Drawing.Point.Create(96, 312);
  Self.btiniciar.Name := ´btiniciar´;
  Self.btiniciar.Size := System.Drawing.Size.Create(60, 20);
  Self.btiniciar.TabIndex := 5;
  Self.btiniciar.Text := ´Iniciar´;
  Include(Self.btiniciar.Click, Self.btiniciar_Click);
  // 
  // btparar
  // 
  Self.btparar.Location := System.Drawing.Point.Create(164, 312);
  Self.btparar.Name := ´btparar´;
  Self.btparar.Size := System.Drawing.Size.Create(60, 20);
  Self.btparar.TabIndex := 6;
  Self.btparar.Text := ´Parar´;
  Include(Self.btparar.Click, Self.btparar_Click);
  //
  // txtCaminho
  // 
  Self.txtCaminho.Location := System.Drawing.Point.Create(104, 40);
  Self.txtCaminho.Name := ´txtCaminho´;
  Self.txtCaminho.Size := System.Drawing.Size.Create(120, 21);
  Self.txtCaminho.TabIndex := 7;
  Self.txtCaminho.Text := ´´;
  // 
  // DropArquivos
  // 
  Self.DropArquivos.DropDownStyle := System.Windows.Forms.ComboBoxStyle.DropDownList;
  Self.DropArquivos.Items.AddRange(TArrayOfSystem_Object.Create(´*.txt´, ´*.´ +
        ´jpg´, ´*.doc´));
  Self.DropArquivos.Location := System.Drawing.Point.Create(112, 100);
  Self.DropArquivos.Name := ´DropArquivos´;
  Self.DropArquivos.Size := System.Drawing.Size.Create(112, 21);
  Self.DropArquivos.TabIndex := 8;
  // 
  // txtmensagem
  // 
  Self.txtmensagem.Location := System.Drawing.Point.Create(8, 136);
  Self.txtmensagem.Name := ´txtmensagem´;
  Self.txtmensagem.Size := System.Drawing.Size.Create(216, 21);
  Self.txtmensagem.TabIndex := 9;
  Self.txtmensagem.Text := ´´;
  // 
  // Label5
  // 
  Self.Label5.AutoSize := True;
  Self.Label5.Location := System.Drawing.Point.Create(8, 70);
  Self.Label5.Name := ´Label5´;
  Self.Label5.Size := System.Drawing.Size.Create(230, 17);
  Self.Label5.TabIndex := 10;
  Self.Label5.Text := ´(Caminho completo da pasta com ´´\´´ no final)´;
  // 
  // lblaviso
  //
  Self.lblaviso.AutoSize := True;
  Self.lblaviso.Font := System.Drawing.Font.Create(´Tahoma´, 8.25, System.Drawing.FontStyle.Bold, 
      System.Drawing.GraphicsUnit.Point, (Byte(0)));
  Self.lblaviso.ForeColor := System.Drawing.SystemColors.ActiveCaption;
  Self.lblaviso.Location := System.Drawing.Point.Create(8, 312);
  Self.lblaviso.Name := ´lblaviso´;
  Self.lblaviso.Size := System.Drawing.Size.Create(48, 17);
  Self.lblaviso.TabIndex := 11;
  Self.lblaviso.Text := ´lblaviso´;
  Include(Self.lblaviso.Click, Self.Label6_Click);
  // 
  // listArquivo
  // 
  Self.listArquivo.Location := System.Drawing.Point.Create(8, 188);
  Self.listArquivo.Name := ´listArquivo´;
  Self.listArquivo.Size := System.Drawing.Size.Create(216, 69);
  Self.listArquivo.TabIndex := 12;
  // 
  // Label6
  //
  Self.Label6.AutoSize := True;
  Self.Label6.Location := System.Drawing.Point.Create(8, 264);
  Self.Label6.Name := ´Label6´;
  Self.Label6.Size := System.Drawing.Size.Create(127, 17);
  Self.Label6.TabIndex := 13;
  Self.Label6.Text := ´Último Arquivo Alterado:´;
  // 
  // lbNomearquivo
  // 
  Self.lbNomearquivo.Location := System.Drawing.Point.Create(8, 280);
  Self.lbNomearquivo.Name := ´lbNomearquivo´;
  Self.lbNomearquivo.Size := System.Drawing.Size.Create(216, 16);
  Self.lbNomearquivo.TabIndex := 14;
  Self.lbNomearquivo.Text := ´Label7´;
  // 
  // TWinForm2
  // 
  Self.AutoScaleBaseSize := System.Drawing.Size.Create(5, 14);
  Self.ClientSize := System.Drawing.Size.Create(232, 334);
  Self.Controls.Add(Self.lbNomearquivo);
  Self.Controls.Add(Self.Label6);
  Self.Controls.Add(Self.listArquivo);
  Self.Controls.Add(Self.lblaviso);
  Self.Controls.Add(Self.Label5);
  Self.Controls.Add(Self.txtmensagem);
  Self.Controls.Add(Self.DropArquivos);
  Self.Controls.Add(Self.txtCaminho);
  Self.Controls.Add(Self.btparar);
  Self.Controls.Add(Self.btiniciar);
  Self.Controls.Add(Self.Label4);
  Self.Controls.Add(Self.Label3);
  Self.Controls.Add(Self.Label2);
  Self.Controls.Add(Self.Label1);
  Self.Font := System.Drawing.Font.Create(´Tahoma´, 8.25, System.Drawing.FontStyle.Regular,
      System.Drawing.GraphicsUnit.Point, (Byte(0)));
  Self.Name := ´TWinForm2´;
  Self.Text := ´Monitor de Pastas´;
  Include(Self.Load, Self.TWinForm2_Load);
  Self.ResumeLayout(False);
end;
{$ENDREGION}

procedure TWinForm2.Dispose(Disposing: Boolean);
begin
  if Disposing then
  begin
    if Components <> nil then
      Components.Dispose();
  end;
  inherited Dispose(Disposing);
end;

constructor TWinForm2.Create;
begin
  inherited Create;
  //
  // Required for Windows Form Designer support
  //
  InitializeComponent;
  FWatcher := FileSystemWatcher.Create;
  // path do diretório a ser monitorado
  FWatcher.Path := ´C:\´;
  // especificação dos arquivos a serem monitorados
  FWatcher.Filter := ´*.txt´;
  // o que vai ser monitorado
  FWatcher.NotifyFilter := NotifyFilters.LastWrite;
  Include(FWatcher.Changed, FileChanged);
  FWatcher.EnableRaisingEvents := True;
  cont := 0;
  //
  // TODO: Add any constructor code after InitializeComponent call
  //
end;

procedure TWinForm2.TWinForm2_Load(sender: System.Object; e: System.EventArgs);
begin
  lblAviso.Text := ´Parado!´;
  btparar.Enabled := false;
  lbNomearquivo.Text := ´Não houve alteração desde a inicialização.´;
end;

procedure TWinForm2.btparar_Click(sender: System.Object; e: System.EventArgs);
begin
  lblAviso.Text := ´Parado!´;
  txtCaminho.Enabled := true;
  dropArquivos.Enabled := true;
  btIniciar.Enabled := true;
  btParar.Enabled := false;
  // PARANDO O MONITORAMENTO
  FWatcher.EnableRaisingEvents := false;
end;

procedure TWinForm2.Label6_Click(sender: System.Object; e: System.EventArgs);
begin

end;

procedure TWinForm2.btiniciar_Click(sender: System.Object; e: System.EventArgs);
var
  item : &object;
begin
 if txtCaminho.Text = ´´ then
  begin
   MessageBox.Show(´Indique o caminho do diretório com "\" no final!´,´AVISO MONITOR!´);
   txtCaminho.Select;
   end
   else
    begin
    if dropArquivos.SelectedIndex = -1 then
     begin
      MessageBox.Show(´Selecione a extensão que deseja monitorar!´,´AVISO MONITOR!´);
      dropArquivos.Select;
      end
      else
       begin
        // SETA CAMINHO DA PASTA, FILTRO E INÍCIA MONITORAMENTO
        FWatcher.Path := txtCaminho.Text;
        FWatcher.Filter := dropArquivos.SelectedText;
        FWatcher.NotifyFilter := NotifyFilters.LastWrite;
        Include(FWatcher.Changed, FileChanged);
        FWatcher.EnableRaisingEvents := true;
        txtCaminho.Enabled := false;
        dropArquivos.Enabled := false;
        btIniciar.Enabled := false;
        btParar.Enabled := true;
        lblAviso.Text := ´Ativo!´;
        cont := 0;
        listArquivo.Items.Clear;
        for item in Directory.GetFiles(txtCaminho.Text) do
         begin
          cont := cont + 1;
          listArquivo.Items.Add(item);
         end;
        txtMensagem.Text := ´Arquivos monitorados:  ´ +cont.ToString();
      end;
   end;
end;

procedure TWinForm2.FileChanged(Sender: TObject;
  E: System.IO.FileSystemEventArgs);
var
  item : &object;
begin
  // E.ChangeType diz qual mudança ocorreu
  // E.FullPath é o caminho para o arquivo afetado
  // E.Name é o nome do arquivo afetado
  cont := 0;
  listArquivo.Items.Clear;
  for item in Directory.GetFiles(txtCaminho.Text) do
   begin
    cont := cont + 1;
    listArquivo.Items.Add(item);
   end;
  txtMensagem.Text := ´Arquivos monitorados:  ´ +cont.ToString();
  lbNomeArquivo.Text := e.Name.ToString();
end;

end.


Sanses


GOSTEI 0
POSTAR