打印本文 打印本文 关闭窗口 关闭窗口
Simulate the pressing of keyboard keys
作者:武汉SEO闵涛  文章来源:敏韬网  点击数2602  更新时间:2009/4/23 18:27:17  文章录入:mintao  责任编辑:mintao
begin
        PostMessage(hWindow, WM_KEYDOWN, key, lParam);
        PostMessage(hWindow, WM_KEYUP, key, lParam or $C0000000);
      end;
      (* process the messages *)
      Application.ProcessMessages;

      (* restore the old key state map *)
      SetKeyboardState(pKeyBuffers^[1]);
    finally
      (* free the memory for the key state buffers *)
      if pKeyBuffers <> nil then
        Dispose(pKeyBuffers);
    end{ If }
  end;
end{ PostKeyEx }

// Example:

procedure TForm1.Button1Click(Sender: TObject);
var
  targetWnd: HWND;
begin
  targetWnd := FindWindow(''''notepad''''nil)
    if targetWnd <> 0 then
    begin
      PostKeyExHWND(targetWnd, Ord(''''I''''), [ssAlt], False);
  end;
end;

{***********************************************************}
{3. With SendInput API}

// Example: Send text
procedure TForm1.Button1Click(Sender: TObject);
const
   Str: string = ''''writing writing writing'''';
var
  Inp: TInput;
  I: Integer;
begin
  Edit1.SetFocus;

  for I := 1 to Length(Str) do
  begin
    // press
    Inp.Itype := INPUT_KEYBOARD;
    Inp.ki.wVk := Ord(UpCase(Str[i]));
    Inp.ki.dwFlags := 0;
    SendInput(1, Inp, SizeOf(Inp));

    // release
    Inp.Itype := INPUT_KEYBOARD;
    Inp.ki.wVk := Ord(UpCase(Str[i]));
    Inp.ki.dwFlags := KEYEVENTF_KEYUP;
    SendInput(1, Inp, SizeOf(Inp));

    Application.ProcessMessages;
    Sleep(80);
  end;
end;

// Example: Simulate Alt+Tab
procedure SendAltTab;
var
  KeyInputs: array of TInput;
  KeyInputCount: Integer;

  procedure KeybdInput(VKey: Byte; Flags: DWORD);
  begin
    Inc(KeyInputCount);
    SetLength(KeyInputs, KeyInputCount);
    KeyInputs[KeyInputCount - 1].Itype := INPUT_KEYBOARD;
    with  KeyInputs[KeyInputCount - 1].ki do
    begin
      wVk := VKey;
      wScan := MapVirtualKey(wVk, 0);
      dwFlags := KEYEVENTF_EXTENDEDKEY;
      dwFlags := Flags or dwFlags;
      time := 0;
      dwExtraInfo := 0;
    end;
  end;
begin
  KeybdInput(VK_MENU, 0);                // Alt
  KeybdInput(VK_TAB, 0);                 // Tab
  KeybdInput(VK_TAB, KEYEVENTF_KEYUP);   // Tab
  KeybdInput(VK_MENU, KEYEVENTF_KEYUP); // Alt
  SendInput(KeyInputCount, KeyInputs[0], SizeOf(KeyInputs[0]));
end;


上一页  [1] [2] [3] 

打印本文 打印本文 关闭窗口 关闭窗口