質問

I have this code right here that modifies the clipboard and then restores it back:

function SetClipText(szText:WideString):Boolean;
var
  pData:  DWORD;
  dwSize: DWORD;
begin
  Result := FALSE;
  if OpenClipBoard(0) then
  begin
    dwSize := (Length(szText) * 2) + 2;
    if dwSize <> 0 then
    begin
      pData := GlobalAlloc(MEM_COMMIT, dwSize);
      if pData <> 0 then
      begin
        CopyMemory(Pointer(pData), @szText[1], dwSize - 2);
        if SetClipBoardData(CF_UNICODETEXT, pData) <> 0 then
          Result := TRUE;
      end;
    end;
    CloseClipBoard;
  end;
end;

function GetClipText(var szText:WideString):Boolean;
var
  hData:  DWORD;
  pData:  Pointer;
  dwSize: DWORD;
begin
  Result := FALSE;
  if OpenClipBoard(0) then
  begin
    hData := GetClipBoardData(CF_UNICODETEXT);
    if hData <> 0 then
    begin
      pData := GlobalLock(hData);
      if pData <> nil then
      begin
        dwSize := GlobalSize(hData);
        if dwSize <> 0 then
        begin
          SetLength(szText, (dwSize div 2) - 1);
          CopyMemory(@szText[1], pData, dwSize);
          Result := TRUE;
        end;
        GlobalUnlock(DWORD(pData));
      end;
    end;
    CloseClipBoard;
  end;
end;
var
 OldClip : WideString;
begin
 repeat until GetClipText  (OldClip);
 repeat until SetClipText  ('NewClipBoardText');
 // PASTE
 keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, 0), 0, 0);
 keybd_event(Ord('V'), MapVirtualKey(Ord('V'), 0), 0, 0);
 keybd_event(Ord('V'), MapVirtualKey(Ord('V'), 0), KEYEVENTF_KEYUP, 0);
 keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, 0), KEYEVENTF_KEYUP, 0);
 repeat until SetClipText  (OldClip);
end.     

I use keybd_event to paste new clipboard text to a window (e.g. notepad). It seems like that keybd_event is so fast, that repeat until SetClipText (OldClip); get's called before the keys got pressed. Is there way to check when and if the keys were pressed?

役に立ちましたか?

解決

keybd_event never fails. It merely places they event that you specify into the currently active input queue.

Because the function is asynchronous the keyboard event is not processed until the other application gets round to processing it. So, most likely the other application has not processed the keyboard event by the time you call SetClipText. You can't expect to know when a particular keyboard event is processed, unless you have control of the other application. But in that case you would not be communicating with it by faking input.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top