与OCaml Graphics的交互性

时间:2016-01-09 16:32:50

标签: user-interface events ocaml action

嘿伙计我并不是一个OCaml精明的人,但是我必须使用标准的图形模块而不是lablgtk来编写一个小的GUI,我想知道它如何在Graphics中用于监听按键和鼠标移动等事件,文档似乎有些神秘,有些人可以给我一个小例子吗?

提前致谢, 科林

1 个答案:

答案 0 :(得分:1)

此代码使用OCaml Graphics模块在图形窗口中显示用户的鼠标位置和按键:

open Graphics
open Printf

(* Displays mouse position and keys pressed in the graphics window,                                                            
   and exits if q is pressed. *)
let rec loop () =
  let e = wait_next_event [Mouse_motion; Key_pressed] in

  let mouse_description = sprintf "Mouse position: %d,%d" e.mouse_x e.mouse_y in
  let key_description = if e.keypressed then sprintf "Key %c was pressed" e.key else "" in

  clear_graph ();
  moveto 0 100; draw_string key_description;
  moveto 0 0; draw_string mouse_description;

  if e.key <> 'q' then loop () else ()

let () =
  open_graph "";
  loop ();
  close_graph ();