gpt4 book ai didi

Delphi TPrinter 和错误 217

转载 作者:行者123 更新时间:2023-12-02 02:59:06 30 4
gpt4 key购买 nike

谁能解释一下它是如何工作的(Delphi XE2 在 Windows10 上运行)?

在一个简约的应用程序中 - 带有两个按钮的表单 - 具有以下代码:

procedure TForm2.Button1Click(Sender: TObject);
begin
Printer.BeginDoc;
Printer.Canvas.TextOut(10,10,'Hello World');
Printer.EndDoc;
end;

procedure TForm2.Button2Click(Sender: TObject);
var
MyPrinter : TPrinter;
begin
MyPrinter := Printer;
MyPrinter.BeginDoc;
MyPrinter.Canvas.TextOut(10,10,'Hello World');
MyPrinter.EndDoc;
MyPrinter.Free;
end;

如果我单击 Button1,程序会在我的默认打印机上打印“Hello World”,并在我关闭它时正常关闭(使用关闭按钮)。相反,如果我单击 Button2,程序将打印相同的页面,但现在当我使用关闭按钮关闭时,我会收到错误 217 消息。

我在 Delphi 文档中找不到有关如何使用 Printer 函数和 TPrinter 变量的说明。我很高兴使用 Button1 技术的衍生技术进行打印 - 如果确认这是“防弹”方法,但想了解为什么 Button2 方法不起作用。我是否应该假设释放我实例化的任何 TPrinter 对象不是我的责任,还是有更清晰的解释?

最佳答案

当您运行此代码时:

  MyPrinter := Printer;
MyPrinter.BeginDoc;
MyPrinter.Canvas.TextOut(10,10,'Hello World');
MyPrinter.EndDoc;
MyPrinter.Free;

Printer 在函数退出时被删除。因此,当应用程序终止时,它会尝试再次删除它,并且您会收到错误。更重要的是,如果您尝试第二次运行此代码,它也会引发。 MyPrinter 只是一个指向全局 TPrinter 对象的指针,由 Printer 函数返回。你不应该删除那些不是你创建的东西。

打印机功能的文档:

Returns a global instance of TPrinter to manage interaction with the printer.

Printer creates an instance of a global TPrinter object the first time it is called. Use the Printer function to print using the TPrinter object.

Note: The global TPrinter object is freed automatically when the application shuts down. After a call to SetPrinter, the printer that is returned is not automatically freed. It is the caller's responsibility to either free the return value, or replace it using another call to SetPrinter and to free the substitute printer that the second SetPrinter call returns.

关于Delphi TPrinter 和错误 217,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44015192/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com