检测窗口关闭的OCaml Graphics

3

我在图形文档中没有找到关于窗口关闭检测的详细信息。如何检测它,以便在关闭时触发一个操作?

谢谢。

1个回答

0
使用一个简单的测试程序(在本答案的末尾包含)并手动关闭窗口告诉我们会引发以下异常:
Fatal error: exception Graphics.Graphic_failure("fatal I/O error")

这意味着我们可以通过使用异常处理程序来处理窗口关闭的情况。
try
  (* Here goes the code opening and manipulating the window *)
with
  | Graphic_failure("fatal I/O error") ->
  (* Here goes the code handling the window being closed manually*)

测试程序(你需要运行ocamlc graphics.cma test.ml -o test编译它):

open Graphics

let rec loop () = loop ()
let () =
(*
  try
*)
    Graphics.open_graph " 400x600";
    loop ()
(*
  with
    | Graphic_failure("fatal I/O error") ->
      print_string "Caught exception";
      print_newline ()
*)

对我来说,它引发了 Graphic_failure("Xlib error: BadDrawable (invalid Pixmap or Window parameter)") 错误... 另外我的应用程序有一些图形但是由终端控制,类似于解释器,所以我没有事件循环。我仍然有一个命令循环,所以我可以在发送命令后捕获异常... 因此,一个临时解决方案是匹配 Graphic_failure("fatal I/O error")Graphic_failure("Xlib error: BadDrawable (invalid Pixmap or Window parameter)"),但是我怎么知道是否还有其他异常需要捕获呢? - Nicolas Scotto Di Perto
即使我在主函数中尝试捕获这些异常,结果仍然是致命错误。 我已经用try match将启动命令的代码(文本和图形)与上面的Graphic_failure包围起来,但没有帮助。 我还尝试匹配Graphic_failure _,但仍然没有帮助... - Nicolas Scotto Di Perto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接