Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   FireMonkey (https://www.clubdelphi.com/foros/forumdisplay.php?f=50)
-   -   Ayuda a pasar este código a firemonkey. (https://www.clubdelphi.com/foros/showthread.php?t=85794)

elmago00 06-05-2014 20:43:42

Ayuda a pasar este código a firemonkey.
 
hola,
anteriormente el señor ecfisa.
me ayudo a crear un editor hexadecimal, funciona bien en VCL. pero necesito tenerlo en firemonkey.
Código Delphi [-]
implementation 
 
procedure DumpFile(aFileName:TFileName; SG: TStringGrid; const BPF: Word);
var
  c, i, r: integer;
  ascii: string;
  aux: Byte;
begin
  with TMemoryStream.Create do
  try
    LoadFromFile(aFileName);
    // configurar StringGrid
    SG.Options:= SG.Options - [goVertLine] - [goHorzLine];
    SG.Font.Name:= 'Courrier';
    SG.Font.Size:= 10;
    SG.ColWidths[0]:= 80;
    SG.Cells[0,0]:= 'Offset(h)';
    SG.ColCount:= BPF+2;
    SG.ColWidths[SG.ColCount-1]:= SG.Canvas.TextWidth('X') * BPF;
    SG.Cells[SG.ColCount-1,0]:= 'ASCII';
    for i:= 0 to BPF-1 do
    begin
      SG.ColWidths[i+1]:= 30;
      SG.Cells[i+1,0]:= IntToHex(i,2);
    end;
    SG.RowCount:= Size div BPF;
    // cargar en StringGrid
    Seek(0, soBeginning);
    c:= 0;
    r:= SG.FixedRows;
    while c < Size do
    begin
      SG.Cells[0, r]:= Format('%s',[IntToHex(c, 8)]);
      ascii:= EmptyStr;
      i:= 0;
      while (i < BPF)and(i+c < Size) do
      begin
        Read(aux, SizeOf(Byte));
        SG.Cells[i+1,r]:= IntToHex(aux,2);
        if aux = 0 then aux := 46;
        ascii:= ascii + Chr(aux);
        Inc(i);
      end;
      SG.Cells[SG.ColCount-1,r]:= Format('%s',[ascii]);
      Inc(c, BPF);
      Inc(r);
    end;
  finally
    Free;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ComboBox1.Items.CommaText:= '8,10,16,24,32,48,64,128,255';
  ComboBox1.ItemIndex:= 2;
end;

procedure TForm1.btnFileClick(Sender: TObject);
begin
  with OpenDialog1 do
  begin
    Filter:= '*.*';
    if Execute then
    begin
      Caption:= FileName;
      DumpFile(FileName, StringGrid1,
        StrToInt(ComboBox1.Items[ComboBox1.ItemIndex]) );
    end;
  end;
end;



procedure SaveDump(aFileName:TFileName; SG: TStringGrid);
var
  c,r: Integer;
  s: string;
begin
  with TStringList.Create do
  try
    for r:= SG.FixedRows to SG.RowCount-1 do
    begin
      s:= '';
      for c:= 0 to SG.ColCount-1 do s:= s + SG.Cells[c,r] + ' ';
      SetLength(s,Length(s)-1);
      Add(s);
    end;
    SaveToFile(aFileName);
  finally
    Free;
  end;
end;
...

procedure TForm1.btnSaveToTxtClick(Sender: TObject);
begin
  with SaveDialog1 do
  begin
    Filter:= '*.txt';
    DefaultExt:= '*.txt';
    if Execute then
      SaveDump(FileName, StringGrid1);
  end;
end;

sera posible pasar este código a firemonkey, sin usar un Control StringGrid. es decir que se almacene en una variable, y no en StringGrid. pero sino, lo mas importante para mi es pasar este código a firemonkey. yo hago el resto.

muchas gracias por su ayuda.

nlsgarcia 06-05-2014 21:03:01

elmago00,

Cita:

Empezado por elmago00
...¿Sera posible pasar este código a Firemonkey, sin usar un Control StringGrid?...es decir que se almacene en una variable...

Pregunto :

1- ¿Por que no un control TStringGrid? :confused:

2- ¿Que control sugieres usar en lugar del control TStringGrid?.

3- ¿Cuando te refieres a una variable exactamente que quieres decir y por que? :confused:

4- ¿Que versión de Delphi utilizas?.

Espero sea útil :)

Nelson.

elmago00 06-05-2014 21:09:37

gracias por responder Nelson.
veras es que lo intento hacer es abrir el archivo, y editarlo automáticamente, buscando la dirección y la cantidad de caracteres que le siguen. luego reemplazarlos por los que yo pongo. por eso decía si podía hacer lo mismo pero almacenarlo en una variable TStringGrid, sin usar el componente.

pero si no es posible. el interés mayor mio es pasarlo a firemonkey para hacer yo el resto, que es buscar la dirección mas el hexadecimal y reemplazarlo.

uso XE3.

parece algo complejo verdad? pero se resume en pasarlo a firemonkey, ya sea un componente TStringGrid o una variable. cualquiera esta bien. siempre que me permita realizar la búsqueda para hacer lo que necesito.

nlsgarcia 06-05-2014 21:26:28

elmago00,

Cita:

Empezado por elmago00
...lo intento hacer es abrir el archivo, y editarlo automáticamente, buscando la dirección y la cantidad de caracteres que le siguen. luego reemplazarlos por los que yo pongo. por eso decía si podía hacer lo mismo pero almacenarlo en una variable TStringGrid, sin usar el componente...

Pregunto:

1- ¿Cuando indicas buscar por dirección te refieres al Offset (Fila) y los Bytes (Columna) que se muestran en el TStringGrid del ejemplo?.

2- ¿Cuando te refieres a almacenarlo en una variable TStringGrid pero sin el componente, te refieres a poder usarlo por código pero sin la parte visual del mismo?.

Espero sea útil :)

Nelson.

elmago00 06-05-2014 21:33:27

exacto usarlo pero sin que el usuario visualice el componente.
la búsqueda la realizo por "Offset" y reemplazo una determinada cantidad de byte(el hexadecimal) no los modifico todos solo unos cuantos, y luego guardo el archivo.

nlsgarcia 06-05-2014 21:41:23

elmago00,

Cita:

Empezado por elmago00
...exacto usarlo pero sin que el usuario visualice el componente...

Ok, veré que puedo hacer :rolleyes:

Pregunto: ¿Cual es la finalidad de este trabajo? :confused:

Nelson.

elmago00 06-05-2014 21:45:10

solo poder abrir un archivo en hexadecimal, y editarlo automáticamente, para un programa que estamos desarrollando.
no es con fines comerciales, ni nada eso.

Casimiro Notevi 06-05-2014 21:45:23

Cita:

Empezado por nlsgarcia (Mensaje 476098)
elmago00,


Ok, veré que puedo hacer :rolleyes:

Pregunto: ¿Cual es la finalidad de este trabajo? :confused:

Nelson.

Me apunto, me gustaría saberlo :)

nlsgarcia 06-05-2014 21:57:58

elmago00,

Cita:

Empezado por elmago00
...solo poder abrir un archivo en hexadecimal, y editarlo automáticamente...

Eso lo entiendo :rolleyes: , mi pregunta se refiere a:

1- ¿Por que este tipo de procesamiento?, ¿Sabes que pontencialmente estas construyendo un virus? :confused:

2- ¿Cuales son los detalles de la aplicación que quieres realizar?.

3- ¿Por que FireMonkey y no VCL?, ¿Es una aplicación multiplataforma?.

Espero sea útil :)

Nelson.

elmago00 07-05-2014 04:24:58

lo siento no comprendí bien tu pregunta.
lo necesito en firemonkey, por que el software principal esta así. y no podemos mover a VCL. por que el código fuente es mas 40 mil lineas de código.

no tiene nada que ver con virus.
conoces los editores hexadecimales. bien pues eso es lo que necesito, por que el software debe editar un archivo, buscar la dirección que debe cambiar para poder cargar ese archivo.


solo necesito ese código en firemonkey. si es un componente stringGrid o no es lo de menos. solo que no querremos que el usuario haga el cambio, por que el no sabrá que esta insertando como reemplazo a la linea hexadecimal. solo eso.

hagamos una cosa. se que no crees lo que digo.
solo detallen las propiedades que tiene este código pero en firemonkey. por que el StringGrid no funciona igual que en VCL.
yo hago el resto.

gracias por responder a mis consultas.

nlsgarcia 07-05-2014 08:56:15

elmago00,

Cita:

Empezado por elmago00
...solo detallen las propiedades que tiene este código pero en FireMonkey...

Revisa este código:
Código Delphi [-]
unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
  System.Variants, System.UIConsts, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
  FMX.StdCtrls, FMX.ListBox, FMX.Layouts, FMX.Grid;

type

  TColumnAccess = class(TColumn)
  end;

  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    ComboBox1: TComboBox;
    OpenDialog1: TOpenDialog;
    SaveDialog1: TSaveDialog;
    Button1: TButton;
    Button2: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure DumpFile(aFileName:TFileName; SG: TStringGrid; const BPF: Word);
var
  c, i, r: Integer;
  Ascii: String;
  Aux: Byte;
  Col, Row: Integer;
  CellCtrl: TStyledControl;

begin

  with TMemoryStream.Create do
  try

    LoadFromFile(aFileName);

    // Configurar StringGrid

    SG.ShowHeader := False;
    SG.ShowHorzLines := False;
    SG.ShowVertLines := False;

    for i := 1 to BPF + 2 do
       SG.AddObject(TStringColumn.Create(nil));

    SG.RowCount:= Size div BPF;

    for Row := 0 to SG.RowCount - 1 do
    begin
       for Col := 0 to SG.ColumnCount - 1 do
       begin

          Application.ProcessMessages;

          CellCtrl := TColumnAccess(SG.Columns[Col]).CellControlByRow(Row);
          if ( CellCtrl <> nil ) and (CellCtrl is TTextCell) then
          begin

             TTextCell(CellCtrl).StyledSettings := [];
             TTextCell(CellCtrl).Font.Family := 'Courrier New';
             TTextCell(CellCtrl).Font.Size := 10;
             TTextCell(CellCtrl).FontColor := claBlack;
             TTextCell(CellCtrl).Font.Style := [];
             TTextCell(CellCtrl).TextAlign := TTextAlign.taCenter;

             if (Col = 0) then
                SG.Columns[Col].Width := 80;

             if (Col <> SG.ColumnCount - 1) and (Col <> 0) then
                SG.Columns[Col].Width := 30;

             if (Col = SG.ColumnCount - 1) then
                SG.Columns[Col].Width := SG.Canvas.TextWidth('X') * BPF;

          end;
       end;
    end;

    SG.Cells[0,0]:= 'Offset(h)';
    SG.Cells[SG.ColumnCount-1,0]:= 'ASCII';

    for i:= 0 to BPF-1 do
    begin
      SG.Cells[i+1,0]:= IntToHex(i,2);
    end;

    // Cargar StringGrid

    Seek(0, soBeginning);
    c:= 0;
    r:= 1;
    while c < Size do
    begin
      SG.Cells[0, r]:= Format('%s',[IntToHex(c, 8)]);
      Ascii:= EmptyStr;
      i:= 0;
      while (i < BPF)and(i+c < Size) do
      begin
        Read(Aux, SizeOf(Byte));
        SG.Cells[i+1,r]:= IntToHex(Aux,2);
        if Aux = 0 then Aux := 46;
        Ascii:= Ascii + Chr(Aux);
        Inc(i);
      end;
      SG.Cells[SG.ColumnCount-1,r]:= Format('%s',[Ascii]);
      Inc(c, BPF);
      Inc(r);
    end;
  finally
    Free;
  end;
end;

// Salvar StringGrig a Archivo TXT
procedure SaveDump(aFileName:TFileName; SG: TStringGrid);
var
  c,r: Integer;
  s: String;
begin
  with TStringList.Create do
  try
    for r:= 0 to SG.RowCount-1 do
    begin
      s:= '';
      for c:= 0 to SG.ColumnCount-1 do s:= s + SG.Cells[c,r] + ' ';
      SetLength(s,Length(s)-1);
      Add(s);
    end;
    SaveToFile(aFileName);
  finally
    Free;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ComboBox1.Items.CommaText:= '8,10,16,24,32,48,64,128,255';
  ComboBox1.ItemIndex:= 2;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  with OpenDialog1 do
  begin
    Filter:= '*.*';
    if Execute then
    begin
      Caption:= FileName;
      DumpFile(FileName, StringGrid1,
        StrToInt(ComboBox1.Items[ComboBox1.ItemIndex]) );
    end;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  with SaveDialog1 do
  begin
    Filter:= '*.txt';
    DefaultExt:= '*.txt';
    if Execute then
      SaveDump(FileName, StringGrid1);
  end;
end;

end.
El código anterior en Delphi XE4 bajo Windows 7 Professional x32, es la implementación del código del Msg #1 en FireMonkey HD, como se muestra en la siguiente imagen:



Espero sea útil :)

Nelson.

elmago00 07-05-2014 10:45:00

gracias Nelson por ayudarme. ya es de madrugada y ustedes me siguen ayudando. mil gracias.

tu código solo tiene un contraste, yo como te dije antes, uso XE3.
y me da dos errores el primero dice:

TTextCell no contiene ningún miembro con el nombre StyledSettings.
es esta linea
Código Delphi [-]
TTextCell(CellCtrl).StyledSettings := [];

veo que tu usas algunas clases que XE3 no están disponibles, como ser: FMX.StdCtrls;

el segundo problema es que abre el archivo pero en blanco, el StringGrid no muestra nada.

perdona tanta molestia, pero cuando el cerebro no da, no queda de otra, que pedir ayuda.

elmago00 07-05-2014 11:18:13

intente no usar la opcion
Código Delphi [-]
TTextCell(CellCtrl).StyledSettings := [];
Pero ahora me permite cerrar la venta. : )

nlsgarcia 07-05-2014 16:36:47

elmago00,

Cita:

Empezado por elmago00
...abre el archivo pero en blanco, el StringGrid no muestra nada...

...intente no usar la opción...TTextCell(CellCtrl).StyledSettings := []...

Pregunto:

1- ¿De que tamaño es el archivo en cuestión?.

2- ¿Puedes abrir otros archivos?.

3- ¿La eliminación de la opción mencionada es la única modificación al código propuesto en el Msg #11?.

Espero sea útil :)

Nelson.

nlsgarcia 07-05-2014 19:39:49

elmago00,

Cita:

Empezado por elmago00
...abre el archivo pero en blanco, el StringGrid no muestra nada...

...intente no usar la opción...TTextCell(CellCtrl).StyledSettings := []...

Es probable que el archivo probado sea muy grande (La lectura es Byte a Byte), y por ello tarda en ser visualizado, eso se soluciona con la inclusión de Application.ProcessMessages en el ciclo de carga del TStringGrid.

Revisa este código:
Código Delphi [-]
unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
  System.Variants, System.UIConsts, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
  FMX.StdCtrls, FMX.ListBox, FMX.Layouts, FMX.Grid;

type

  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    ComboBox1: TComboBox;
    OpenDialog1: TOpenDialog;
    SaveDialog1: TSaveDialog;
    Button1: TButton;
    Button2: TButton;
    StatusBar1: TStatusBar;
    Label1: TLabel;
    Button3: TButton;
    Button4: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure DumpFile(aFileName:TFileName; SG: TStringGrid; const BPF: Word);
    procedure SaveDump(aFileName:TFileName; SG: TStringGrid);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  CancelProcess : Boolean;

implementation

{$R *.fmx}

procedure TForm1.DumpFile(aFileName:TFileName; SG: TStringGrid; const BPF: Word);
var
  c, i, r, b : Integer;
  Ascii: String;
  Aux: Byte;
  Col : Integer;

begin

  with TMemoryStream.Create do
  try

    LoadFromFile(aFileName);

    Caption:= Format('FileName = %s , FileSize = %d Bytes', [aFileName, Size]);

    // Configurar StringGrid

    SG.ShowHeader := False;
    SG.ShowHorzLines := False;
    SG.ShowVertLines := False;

    for i := 1 to BPF + 2 do
       SG.AddObject(TStringColumn.Create(nil));

    SG.RowCount:= Size div BPF;

    for Col := 0 to SG.ColumnCount - 1 do
    begin

        if (Col = 0) then
           SG.Columns[Col].Width := 80;

        if (Col <> SG.ColumnCount - 1) and (Col <> 0) then
           SG.Columns[Col].Width := 30;

        if (Col = SG.ColumnCount - 1) then
           SG.Columns[Col].Width := SG.Canvas.TextWidth('X') * BPF;

    end;

    SG.Cells[0,0]:= 'Offset(h)';
    SG.Cells[SG.ColumnCount-1,0]:= 'ASCII';

    for i:= 0 to BPF-1 do
    begin
      SG.Cells[i+1,0]:= IntToHex(i,2);
    end;

    // Cargar en StringGrid

    Seek(0, soBeginning);
    c:= 0;
    r:= 1;
    b := 0;

    while c < Size do
    begin

      Application.ProcessMessages;

      if CancelProcess then
      begin
         CancelProcess := False;
         Break;
      end;

      SG.Cells[0, r]:= Format('%s',[IntToHex(c, 8)]);
      Ascii:= EmptyStr;
      i:= 0;

      while (i < BPF) do
      begin
        Read(Aux, SizeOf(Byte));
        SG.Cells[i+1,r]:= IntToHex(Aux,2);
        if Aux = 0 then Aux := 46;
        Ascii:= Ascii + Chr(Aux);
        Inc(i);
        if (b < Size) then Inc(b);
      end;

      SG.Cells[SG.ColumnCount-1,r]:= Format('%s',[Ascii]);
      Inc(c, BPF);
      Inc(r);
      Label1.Text := Format('Procesado Byte %d de %d',[b, Size]);

    end;

  finally

    Free;

  end;

end;

// Salvar StringGrig a TXT
procedure TForm1.SaveDump(aFileName:TFileName; SG: TStringGrid);
var
  c,r: Integer;
  s: String;
begin
  with TStringList.Create do
  try
    for r:= 0 to SG.RowCount-1 do
    begin
      s:= '';
      for c:= 0 to SG.ColumnCount-1 do s:= s + SG.Cells[c,r] + ' ';
      SetLength(s,Length(s)-1);
      Add(s);
    end;
    SaveToFile(aFileName);
  finally
    Free;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ComboBox1.Items.CommaText:= '8,10,16,24,32,48,64,128,255';
  ComboBox1.ItemIndex:= 2;
end;

// Carga un Archivo en Modo Hexadecimal en un StringGrid
procedure TForm1.Button1Click(Sender: TObject);
begin
  with OpenDialog1 do
  begin
    Filter:= '*.*';
    if Execute then
    begin
      DumpFile(FileName, StringGrid1,
        StrToInt(ComboBox1.Items[ComboBox1.ItemIndex]) );
    end;
  end;
end;

// Salva un Archivo en Modo Hexadecimal en un StringGrid a TXT
procedure TForm1.Button2Click(Sender: TObject);
begin
  with SaveDialog1 do
  begin
    Filter:= '*.txt';
    DefaultExt:= '*.txt';
    if Execute then
      SaveDump(FileName, StringGrid1);
  end;
end;

// Cancela Carga de un Archivo en Modo Hexadecimal en un StringGrid
procedure TForm1.Button3Click(Sender: TObject);
begin
   CancelProcess := True;
end;

// Inicializa el StringGrid
procedure TForm1.Button4Click(Sender: TObject);
var
   i : Integer;
begin
   StringGrid1.RowCount := 0;
   for i := StringGrid1.ColumnCount - 1 downto 0 do
         StringGrid1.Columns[i].DisposeOf;
end;

end.
El código anterior en Delphi XE4 bajo Windows 7 Professional x32, es la versión 2 del código propuesto en el Msg #11, con unas pequeños cambios en el manejo del Visualizador de Archivos en Hexadecimal en FireMonkey, como se muestra en la siguiente imagen:



El código esta disponible en : Visualizador de Archivos en Hexadecimal en FireMonkey

Espero sea útil :)

Nelson.

elmago00 07-05-2014 20:35:26

muchas gracias al fin lo conseguí, se demora un poco, pero no importa. muchas gracias Nelson^\||/^\||/:)
para que fuera compatible con XE3 lo hice asi.

Código Delphi [-]
procedure DumpFile(aFileName:TFileName; SG: TStringGrid; const BPF: Word);
var
  c, i, r, b : Integer;
  Ascii: String;
  Aux: Byte;
  Col : Integer;

begin

  with TMemoryStream.Create do
  try

    LoadFromFile(aFileName);



    // Configurar StringGrid

    SG.ShowHeader := False;
    SG.ShowHorzLines := False;
    SG.ShowVertLines := False;

    for i := 1 to BPF + 2 do
       SG.AddObject(TStringColumn.Create(nil));

    SG.RowCount:= Size div BPF;

    for Col := 0 to SG.ColumnCount - 1 do
    begin

        if (Col = 0) then
           SG.Columns[Col].Width := 80;

        if (Col <> SG.ColumnCount - 1) and (Col <> 0) then
           SG.Columns[Col].Width := 30;

        if (Col = SG.ColumnCount - 1) then
           SG.Columns[Col].Width := SG.Canvas.TextWidth('X') * BPF;

    end;

    SG.Cells[0,0]:= 'Offset(h)';
    SG.Cells[SG.ColumnCount-1,0]:= 'ASCII';

    for i:= 0 to BPF-1 do
    begin
      SG.Cells[i+1,0]:= IntToHex(i,2);
    end;

    // Cargar en StringGrid

    Seek(0, soBeginning);
    c:= 0;
    r:= 1;
    b := 0;

    while c < Size do
    begin

      Application.ProcessMessages;

      if CancelProcess then
      begin
         CancelProcess := False;
         Break;
      end;

      SG.Cells[0, r]:= Format('%s',[IntToHex(c, 8)]);
      Ascii:= EmptyStr;
      i:= 0;

      while (i < BPF) do
      begin
        Read(Aux, SizeOf(Byte));
        SG.Cells[i+1,r]:= IntToHex(Aux,2);
        if Aux = 0 then Aux := 46;
        Ascii:= Ascii + Chr(Aux);
        Inc(i);
        if (b < Size) then Inc(b);
      end;

      SG.Cells[SG.ColumnCount-1,r]:= Format('%s',[Ascii]);
      Inc(c, BPF);
      Inc(r);


    end;

  finally

    Free;

  end;

end;

// Salvar StringGrig a TXT
procedure SaveDump(aFileName:TFileName; SG: TStringGrid);
var
  c,r: Integer;
  s: String;
begin
  with TStringList.Create do
  try
    for r:= 0 to SG.RowCount-1 do
    begin
      s:= '';
      for c:= 0 to SG.ColumnCount-1 do s:= s + SG.Cells[c,r] + ' ';
      SetLength(s,Length(s)-1);
      Add(s);
    end;
    SaveToFile(aFileName);
  finally
    Free;
  end;
end;


{guardar}

procedure TForm12.Button25Click(Sender: TObject);
begin
 with SaveDialog1 do
  begin
    Filter:= '*.txt';
    DefaultExt:= '*.txt';
    if Execute then
      SaveDump(FileName, StringGrid1);
  end;
end;



{abrir}

procedure TForm12.Button6Click(Sender: TObject);
   var
   valor:string;
begin
    valor:='16';
 with OpenDialog1 do
  begin
    Filter:= '*.*';
    if Execute then
    begin
      Caption:= FileName;
      DumpFile(FileName, StringGrid1,
        StrToInt(valor));
    end;
  end;
end;

{cancelar}

procedure TForm12.Button26Click(Sender: TObject);
begin
CancelProcess := True;
end;

gracias a Ecfisa y Nelson.^\||/

ecfisa 07-05-2014 21:14:30

Cita:

Empezado por elmago00 (Mensaje 476095)
gracias por responder Nelson.
veras es que lo intento hacer es abrir el archivo, y editarlo automáticamente, buscando la dirección y la cantidad de caracteres que le siguen. luego reemplazarlos por los que yo pongo. por eso decía si podía hacer lo mismo pero almacenarlo en una variable TStringGrid, sin usar el componente.

Hola elmago00.

En el hilo anterior había interpretado que querias realizar cambios, de allí que usé un componente que te permitiera hacerlos interactivamente, pero si deseas guardarlo en un archivo de texto para trabajar sobre él, también podrías hacer:
Código Delphi [-]
procedure DumpFile(aFileName:TFileName; const BPF: Word);
var
  c, i, r: integer;
  ascii: string;
  linea: string;
  aux: Byte;
begin
  with TMemoryStream.Create do
  try
    LoadFromFile(aFileName);
    Seek(0, soBeginning);
    with TStringList.Create do
    try
      c:= 0;
      while c < Size do
      begin
        linea:= IntToHex(c, 8)+' ';
        ascii:= EmptyStr;
        i:= 0;
        while (i < BPF) and (i+c < Size) do
        begin
          Read(aux, SizeOf(Byte));
          linea:= linea + IntToHex(aux,2) + ' ';
          if aux in [$0..$20,$80..$90] then aux:= Ord('.');
          ascii:= ascii + Chr(aux);
          Inc(i);
        end;
        linea:= linea + ascii ;
        Add(linea);
        Inc(c, BPF);
        Inc(r);
      end;
      SaveToFile(ExtractFilePath(aFileName) +
        ChangeFileExt(ExtractFileName(aFileName), '') + '.HEX');
    finally
      Free;
    end;
  finally
    Free;
  end;
end;

Uso:
Código Delphi [-]
  DumpFile('c:\windows\notepad.exe',16);
El código te genera el archivo en la misma carpeta del archivo orígen, con el mismo nombre, de extensión .HEX y contiene los mismos datos que veías en el StringGrid.

Saludos :)

nlsgarcia 07-05-2014 22:08:54

elmago00,

Cita:

Empezado por elmago00
...al fin lo conseguí...

:) ^\||/

Una pequeña corrección :rolleyes: :
Código Delphi [-]
procedure TForm1.DumpFile(aFileName:TFileName; SG: TStringGrid; const BPF: Word);
var
  c, i, r, b : Integer;
  Ascii: String;
  Aux: Byte;
  Col : Integer;

begin

  with TMemoryStream.Create do
  try

    LoadFromFile(aFileName);

    Caption:= Format('FileName = %s , FileSize = %d Bytes', [aFileName, Size]);

    // Configurar StringGrid

    SG.ShowHeader := False;
    SG.ShowHorzLines := False;
    SG.ShowVertLines := False;

    for i := 1 to BPF + 2 do
       SG.AddObject(TStringColumn.Create(nil));

    SG.RowCount := (Size div BPF) + 1;
    if (Size Mod BPF) <> 0 then
       SG.RowCount := SG.RowCount + 1;

    for Col := 0 to SG.ColumnCount - 1 do
    begin

        if (Col = 0) then
           SG.Columns[Col].Width := 80;

        if (Col <> SG.ColumnCount - 1) and (Col <> 0) then
           SG.Columns[Col].Width := 30;

        if (Col = SG.ColumnCount - 1) then
           SG.Columns[Col].Width := SG.Canvas.TextWidth('X') * BPF;

    end;

    SG.Cells[0,0]:= 'Offset(h)';
    SG.Cells[SG.ColumnCount-1,0]:= 'ASCII';

    for i:= 0 to BPF-1 do
    begin
      SG.Cells[i+1,0]:= IntToHex(i,2);
    end;

    // Cargar en StringGrid

    Seek(0, soBeginning);
    c:= 0;
    r:= 1;
    b := 0;

    while c < Size do
    begin

      Application.ProcessMessages;

      if CancelProcess then
      begin
         CancelProcess := False;
         Break;
      end;

      SG.Cells[0, r]:= Format('%s',[IntToHex(c, 8)]);
      Ascii:= EmptyStr;
      i:= 0;

      while (i < BPF) and (b < Size) do
      begin
        Read(Aux, SizeOf(Byte));
        SG.Cells[i+1,r]:= IntToHex(Aux,2);
        if Aux = 0 then Aux := 46;
        Ascii:= Ascii + Chr(Aux);
        Inc(i);
        if (b < Size) then Inc(b);
      end;

      SG.Cells[SG.ColumnCount-1,r]:= Format('%s',[Ascii]);
      Inc(c, BPF);
      Inc(r);
      Label1.Text := Format('Procesado Byte %d de %d',[b, Size]);

    end;

  finally

    Free;

  end;

end;
El código anterior en Delphi XE4 bajo Windows 7 Professional x32, corrige el código del Msg #15 en los casos en que los archivos a visualizar no sean múltiplos del factor de visualización (BPF), como se muestra en la siguiente imagen:



El código esta disponible en : Visualizador de Archivos en Hexadecimal v2 en FireMonkey

Espero sea útil :)

Nelson.

elmago00 08-05-2014 07:11:54

muchas gracias, agradezco mucho que hayan compartido su experiencia en este lenguaje conmigo. muchas gracias^\||/^\||/:D

elmago00 08-05-2014 08:38:34

aprovecho, para preguntarles, se podrá recuperar el archivo con su extensión original.
pues al hacer el cambio en el archivo después de editarlo, no vuelve a funcionar, por que esta en hexadecimal.
¿se puede recuperar el archivo original, pero después de haberlo modificado?.


La franja horaria es GMT +2. Ahora son las 12:20:30.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi