5

我想将整个屏幕的屏幕截图绘制到 TForm1 画布上。

此代码在 Delphi XE3 中运行良好

procedure TForm1.Button1Click(Sender: TObject);
var
  c,scr: TCanvas;
  r,r2: TRect;
begin

  c := TCanvas.Create;
  scr := TCanvas.Create;
  c.Handle := GetWindowDC(GetDesktopWindow);
  try

    r := Rect(0, 0, 200, 200);
    form1.Canvas.CopyRect(r, c, r);

  finally
    ReleaseDC(0, c.Handle);
    c.Free;
  end;

现在我想先把截图复制到另一个画布上。有没有办法做到这一点而不会出现此错误?

procedure TForm1.Button1Click(Sender: TObject);
var
  c,scr: TCanvas;
  r,r2: TRect;
begin

  c := TCanvas.Create;
  scr := TCanvas.Create;
  c.Handle := GetWindowDC(GetDesktopWindow);
  try

    r := Rect(0, 0, 200, 200);

    scr.CopyRect(r,c,r); <-- Error, canvas does not allow drawing
    form1.Canvas.CopyRect(r, scr, r); <-- Error, canvas does not allow drawing

  finally
    ReleaseDC(0, c.Handle);
    c.Free;
  end;
4

2 回答 2

4

如果您需要使用额外的画布,则必须分配 HDC,例如

var
  WindowHandle:HWND;
  ScreenCanvas,BufferCanvas: TCanvas;
  r,r2: TRect;
  ScreenDC,BufferDC :HDC;
  BufferBitmap : HBITMAP;
begin
  WindowHandle := 0;
  ScreenCanvas := TCanvas.Create;
  BufferCanvas := TCanvas.Create;

  ScreenDC:=GetWindowDC(WindowHandle);
  ScreenCanvas.Handle := ScreenDC;

  BufferDC := CreateCompatibleDC(ScreenDC);
  BufferCanvas.Handle := BufferDC;
  BufferBitmap := CreateCompatibleBitmap(ScreenDC,
                     GetDeviceCaps(ScreenDC, HORZRES),
                     GetDeviceCaps(ScreenDC, VERTRES));
  SelectObject(BufferDC, BufferBitmap);

  try
    r := Rect(0, 0, 200, 200);
    BufferCanvas.CopyRect(r,ScreenCanvas,r);
    form1.Canvas.CopyRect(r, BufferCanvas, r);
  finally
    ReleaseDC(WindowHandle, ScreenCanvas.Handle);
    DeleteDC(BufferDC);
    DeleteObject(BufferBitmap);
    BufferCanvas.Free;
    ScreenCanvas.Free;
  end;
end;
于 2013-04-04T12:47:28.570 回答
1

是时候把我的解决方案扔进锅里了!

procedure TForm1.FormClick(Sender: TObject);
var
  ScreenCanvas: TCanvas;
begin
  ScreenCanvas := TCanvas.Create;
  try
    ScreenCanvas.Handle := GetWindowDC(GetDesktopWindow);
    Win32Check(ScreenCanvas.HandleAllocated);
    Canvas.CopyRect(Canvas.ClipRect, ScreenCanvas, ScreenCanvas.ClipRect);
  finally
    ReleaseDC(GetDesktopWindow, ScreenCanvas.Handle);
    ScreenCanvas.Free;
  end;
end;
于 2013-04-05T08:30:12.807 回答