当前位置 : 主页 > 编程语言 > delphi >

delphi – Canvas不允许绘图

来源:互联网 收集:自由互联 发布时间:2021-06-23
我想从整个屏幕绘制一个截图到TForm1 Canvas. 此代码在Delphi XE3中运行良好 procedure TForm1.Button1Click(Sender: TObject);var c,scr: TCanvas; r,r2: TRect;begin c := TCanvas.Create; scr := TCanvas.Create; c.Handle := GetW
我想从整个屏幕绘制一个截图到TForm1 Canvas.

此代码在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;
如果您需要使用其他画布,则必须分配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;
网友评论