Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Leer/Enviar strings a/desde otra aplicación (https://www.clubdelphi.com/foros/showthread.php?t=88500)

newtron 13-06-2015 12:18:58

Leer/Enviar strings a/desde otra aplicación
 
Hola a tod@s.

Hay una aplicación en VB6 de la cual tengo, desde mi programa delphi, que leer y escribir strings desde y hacia unos controles de texto. He estado echando un vistazo y este hilo que resuelve el amigo ecfisa hace más de lo que me hace falta pero la verdad es que se me hace un poco espeso de descifrar.

¿Alguien me podría poner un ejemplo simple de envio/recepción de cadenas de caracteres desde/hacia otro programa VB6 sabiendo el nombre de los controles del programa VB?.

Gracias y un saludo

nlsgarcia 14-06-2015 06:38:20

newtron,

Cita:

Empezado por newtron
...una aplicación en VB6 de la cual tengo desde mi programa Delphi, que leer y escribir Strings desde y hacia unos Controles de Texto...¿Alguien me podría poner un ejemplo simple de envió/recepción de cadenas de caracteres desde/hacia otro programa VB6 sabiendo el nombre de los controles del programa VB?...

:rolleyes:

Revisa este código:
Código:

Option Explicit

'Código en VB6 de la aplicación que recibe y envía strings por medio de Delphi

Private Sub Command1_Click()

  Dim Msg, Title As String
 
  Msg = Text1 + " " + Text2 + " " + Text3
 
  Title = "VB6"
 
  Call MsgBox(Msg, vbOKOnly + vbInformation, Title)
 
End Sub

Private Sub Command2_Click()
 
  Text1 = Empty
  Text2 = Empty
  Text3 = Empty
 
End Sub

Código Delphi [-]
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Button1: TButton;
    Button2: TButton;
    Label4: TLabel;
    Button3: TButton;
    Button4: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

const
  WindowName : String = 'Recibir Strings con Windows APIs';

var
  Form1: TForm1;
  SL : TStringList;

implementation

{$R *.dfm}

// Obtiene los controles de la ventana seleccionada
function EnumChildWindowsCallback(Window : THandle; SL : TStringList) : LongBool; Stdcall;
var
   Buffer : Array[0..255] of Char;

begin

  if (GetClassName(Window, Buffer, 256) <> 0) then
  begin
     SL.AddObject(Buffer, TObject(Window));
     Result := True;
  end
  else
     Result := False;

end;

// Envia Strings (TEdit.Text) a una aplicación en VB6
procedure TForm1.Button1Click(Sender: TObject);
var
   Window : THandle;
   i,j : Integer;
   Buffer : Array[0..8192] of Char;
   AData : Array[0..2] of String;

begin

   Window := FindWindow(nil, PChar(WindowName));

   if (Window <> 0) then
   begin

      SL := TStringList.Create;

      AData[0] := Edit1.Text;
      AData[1] := Edit2.Text;
      AData[2] := Edit3.Text;

      EnumChildWindows(Window, @EnumChildWindowsCallback, LPARAM(SL));

      j := 2;
      for i := 0 to SL.Count - 1 do
      begin
         if (SL.Strings[i] = 'ThunderRT6TextBox') then
         begin
            StrPCopy(Buffer,AData[j]);
            SendMessage(THandle(SL.Objects[i]), WM_SETTEXT, SizeOf(Buffer), Integer(@Buffer));
            Dec(j);
         end;
      end;

      SL.Free;

   end;

end;

// Recibe Strings (TextBox) de una aplicación en VB6
procedure TForm1.Button2Click(Sender: TObject);
var
   Window : THandle;
   i,j : Integer;
   Buffer : Array[0..8192] of Char;
   AData : Array[0..2] of String;

begin

   Window := FindWindow(nil, PChar(WindowName));

   if (Window <> 0) then
   begin

      SL := TStringList.Create;

      EnumChildWindows(Window, @EnumChildWindowsCallback, LPARAM(SL));

      j := 2;
      for i := 0 to SL.Count - 1 do
      begin
         if (SL.Strings[i] = 'ThunderRT6TextBox') then
         begin
            SendMessage(THandle(SL.Objects[i]), WM_GETTEXT, SizeOf(Buffer), Integer(@Buffer));
            AData[j] := Buffer;
            Dec(j);
         end;
      end;

      Edit1.Text := AData[0];
      Edit2.Text := AData[1];
      Edit3.Text := AData[2];

      SL.Free;

   end;

end;

// MessageDlg
procedure TForm1.Button3Click(Sender: TObject);
var
   MsgApp, MsgUsr : String;

begin

   MsgApp := 'Delphi 7';
   MsgUsr := Edit1.Text + ' ' + Edit2.Text + ' ' + Edit3.Text;
   MessageBox(Handle, PChar(MsgUsr), PChar(MsgApp), MB_OK + MB_ICONINFORMATION);

end;

// Reset TEdit
procedure TForm1.Button4Click(Sender: TObject);
begin
   Edit1.Text := EmptyStr;
   Edit2.Text := EmptyStr;
   Edit3.Text := EmptyStr;
end;

end.
El código anterior en Delphi 7 sobre Windows 7 Professional x32, Permite enviar (TEdit.Text) y recibir (TextBox) Strings hacia y desde un programa en VB6, como se muestra en la siguiente imagen:



Todo el código del ejemplo esta disponible en : SendMessage Delphi 7 & VB6.rar

Nota: En VB6 los controles equivalentes a un TEdit son los TextBox y su ClassName es ThunderRT6TextBox

Revisa esta información:
Espero sea útil :)

Nelson.

newtron 14-06-2015 09:48:10

Gracias Nelson.

¿No hay forma de dirigirme directamente a un "TextBox" por su nombre?. El tema es que tengo que identificar de alguna manera el componente del que quiero enviar/recibir strings y sería lo más fácil en vez de recorrer todos los de la ventana e intentar identificarlo en esa lista.

Saludos

escafandra 14-06-2015 10:09:20

Si conoces el nombre windows de la clase, si, usando FindWindow, pero ten en cuenta que ese nombre no tiene porqué ser idéntico al de VB o delphi.

Hace tiempo escribí una pequeña utilidad, WinInfo, para conocer datos vitales de las ventanas de Windows con el fin de saber, entre otras cosas, el nombre de una clase de ventana.


Saludos.

newtron 14-06-2015 10:18:06

Cita:

Empezado por escafandra (Mensaje 493317)
Si conoces el nombre windows de la clase, si, usando FindWindow, pero ten en cuenta que ese nombre no tiene porqué ser idéntico al de VB o delphi.

Hace tiempo escribí una pequeña utilidad, WinInfo, para conocer datos vitales de las ventanas de Windows con el fin de saber, entre otras cosas, el nombre de una clase de ventana.


Saludos.

Gracias escafandra.

Pero...¿hablamos de la ventana del formulario o del componente "TextBox" que quiero leer/escribir en él?

Saludos

escafandra 14-06-2015 11:04:32

Me refiero a cualquier ventana (componente o control) Usa WinInfo, coloca su cursor "punto de mira" en la ventana que te interese y obten sys daros automáticamente.

Saludos.

newtron 15-06-2015 09:19:22

Ok.

Le echaremos un vistazo.

Gracias y un saludo

ecfisa 15-06-2015 22:09:32

Hola mi amigo.
Cita:

Empezado por newtron (Mensaje 493302)
Hola a tod@s.

Hay una aplicación en VB6 de la cual tengo, desde mi programa delphi, que leer y escribir strings desde y hacia unos controles de texto. He estado echando un vistazo y este hilo que resuelve el amigo ecfisa hace más de lo que me hace falta pero la verdad es que se me hace un poco espeso de descifrar.

No creo que haya soluciónes triviales para resolver lo que buscas...
Estuve pensando como podría simplificar el código del mensaje que citas mas (arriba), y se me ocurre que lo mas adecuado es encapsularlo en una clase y ponerlo en una unidad, eso tal vez no lo haga mas simple, pero le dá seguridad, reusabilidad y claridad en su utilización.
Código Delphi [-]
unit uChildWndText;

interface

uses Windows, SysUtils, Classes, Messages;

type
  TChildWndText = class
  private
    FParentHandle: HWND;
    FWndList: TStrings;
    FWndText : array[0..8192] of Char;
    function FGetText(Index: Integer): string;
    procedure FSetText(Index: Integer; Value: string);
  public
    constructor Create(const WndParentName: string);
    destructor Destroy; override;
    property WindowList  : TStrings read FWndList;
    property ChildrenText[Index: Integer]: string read FGetText write FSetText;
  end;

implementation

function CallbackFn(aHandle: HWND; WndList: TStrings): LongBool; stdcall;
var
  bufName: array[0..255] of Char;
begin
  Result := True;
  if GetClassName(aHandle, bufName, 256) <> 0 then
    WndList.AddObject(bufName, TObject(aHandle));
end;

constructor TChildWndText.Create(const WndParentName: string);
begin
  inherited Create;

  FParentHandle := FindWindow(nil, PChar(WndParentName));
  if FParentHandle = 0 then
    raise Exception.Create('No se encontró una ventana con ese título');

  FWndList := TStringList.Create;
  EnumChildWindows(FParentHandle, @CallbackFn, LPARAM(FWndList));
end;

destructor TChildWndText.Destroy;
begin
  FWndList.Free;
  inherited;
end;

function TChildWndText.FGetText(Index: Integer): string;
begin
  if (Index < 0) or (Index > FWndList.Count-1) then
    raise Exception.Create('Índice fuera de rango');

  SendMessage(HWND(FWndList.Objects[Index]),
    WM_GETTEXT, SizeOf(FWndText), Integer(@FWndText));
  Result := FWndText;
end;

procedure TChildWndText.FSetText(Index: Integer; Value: string);
begin
  if (Index < 0) or (Index > FWndList.Count-1) then
    raise Exception.Create('Índice fuera de rango');
    
  if Value <> FWndList[Index] then
  begin
    StrPCopy(FWndText, Value);
    SendMessage(HWND(FWndList.Objects[Index]),
      WM_SETTEXT, SizeOf(FWndText), Integer(@FWndText));
  end;
end;
end.

Eso te permite, por ejemplo, cargarlo en un ComboBox como en el enlace que mencionas:
Código Delphi [-]
...
implementation

uses uChildWndText;

var
  ChildText : TChildWndText;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ChildText := TChildWndText.Create('Form1');
  ComboBox1.Items.Assign(ChildText.WindowList);
  ComboBox1.ItemIndex := 0;
end;

procedure TForm1.btnGetTextClick(Sender: TObject);
begin
  Memo1.Text := ChildText.ChildrenText[ComboBox1.ItemIndex];
end;

procedure TForm1.btnSetTextClick(Sender: TObject);
begin
  ChildText.ChildrenText[ComboBox1.ItemIndex] := Memo1.Text;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  ChildText.Free;
end;
Pero si conoces los nombres, como mencionas, también de forma directa:
Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
var
  inx: Integer;
  str: string;
begin
  str:= 'NUEVO TEXTO';
  with TChildWndText.Create('Form1') do
  try
    inx := WindowList.IndexOf('TEdit');
    if MessageDlg(Format('Texto actual: %s ¿ Cambia por: %s ?',
      [ChildrenText[inx],str]), mtConfirmation, [mbYes,mbNo],0) = mrYes then
      ChildrenText[inx]:= 'Nuevo Texto';
  finally
    Free;
  end;
end;
También te puede venir muy bién la sugerencia de escafandra que hace uso de la posición del mouse y te ahorra la enumeración al hacer la selección de forma directa.

Saludos :)

newtron 16-06-2015 09:28:56

Ecfisa, gracias por tu aporte al igual que a nlsgarcia y a escafandra.

Al final he solucionado el asunto con vuestros ejemplos y ya me comunico con el programita VB sin problemas.

Gracias por vuestro interés y apuntaros una ronda a mi cuenta. :D


La franja horaria es GMT +2. Ahora son las 15:30:01.

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