how to Simulate Ctrl+ c in Delphi

delphi

Solution

(Let me preface this by saying that using the clipboard for inter-process communication is a bad idea. The clipboard belongs to the user, and your application should only use it as a result of the user choosing to do so.)

If you have text selected in Notepad, this will get the contents into a `TMemo` on a Delphi form (uses just a `TMemo` and `TButton`; add `ClipBrd` to your uses clause):

procedure TForm1.Button1Click(Sender: TObject);
var
  NpWnd, NpEdit: HWnd;
begin
  Memo1.Clear;
  NpWnd := FindWindow('Notepad', nil);
  if NpWnd <> 0 then
  begin
    NpEdit := FindWindowEx(NpWnd, 0, 'Edit', nil);
    if NpEdit <> 0 then
    begin
      SendMessage(NpEdit, WM_COPY, 0, 0);
      Memo1.Lines.Text := Clipboard.AsText;
    end;
  end;
end;

Sample of results:

If the text is not selected first, send it a `WM_SETSEL` message first. Passing values of `0` and '-1' selects all text.

procedure TForm1.Button1Click(Sender: TObject);
var
  NpWnd, NpEdit: HWnd;
begin
  Memo1.Clear;
  NpWnd := FindWindow('Notepad', nil);
  if NpWnd <> 0 then
  begin
    NpEdit := FindWindowEx(NpWnd, 0, 'Edit', nil);
    if NpEdit <> 0 then
    begin
      SendMessage(NpEdit, EM_SETSEL, 0, -1);
      SendMessage(NpEdit, WM_COPY, 0, 0);
      Memo1.Lines.Text := Clipboard.AsText;
    end;
  end;
end;

Problem

is there any way to simulate Ctrl+C command in delphi ? the problem is i want that from another application for example copy a text from Notepad after select the target text .

Original source