在我目前的Project中,这是一个图形数独游戏,我创建了一个按钮板,当你点击按钮时,它被标记出来。标记按钮后,您应该能够按下键盘上的数字,并且应该检索该数字(0..9)(如果按0则为0,如果按1等则为1)。
所以我的问题是:如何获取用户按下的键盘键,如果它是一个数字然后检索它,以便我可以将它放在二维数组中并在标记按钮中显示为文本?
我包含了我的程序的一部分(如果你得到Fsharpx,System.Forms,System.Drawing和其他必要的库,那么编译很好),这样你就可以看到我到目前为止的想法。 / p>
namespace Sudoku
open FSharp.Control.Observable
module Main =
open System.Windows.Forms
open System.Drawing
let sudokuGame = Array2D.init 9 9 (fun x y -> 0)
let form = new Form(Text="Sudoku game", TopMost=true, Width=360, Height=390)
let buttonPos text x y =
let defaultSize = new Size(30,30) in
(new Button(Text=text, Top=x, Left=y, Size=defaultSize, BackColor=Color.Aqua)) :> Control
let gameButtons = [|for y in 1..9 do for x in 1..9 -> (buttonPos "0" (x*30) (y*30))|]
let changeText pos c = (Array.get (gameButtons) (pos)).Text <- c
form.Controls.AddRange gameButtons
let rec obsMerger obsList =
match obsList with
| x1::[] -> x1
| x1::xs -> Observable.merge x1 (obsMerger xs)
| [] -> failwith "No Observables"
let obsList = [for x in 81..(161) -> Observable.map(fun _ -> x) (gameButtons.[x-81].KeyDown)] @ [ for x in 0..80 -> (Observable.map (fun _-> x) ((Array.get(gameButtons)(x)).Click)) ]
let playModeObservables = obsMerger obsList
let rec playMode observable gameField lastPressed = async{
let! somethingObservable = Async.AwaitObservable(observable)
match somethingObservable with
| x when x < 81 && x > -1 -> return! playMode observable gameField x
| x when x > 80 && x < 162 -> changeText lastPressed ((x-80).ToString())
return! playMode observable gameField (x-81)
| _ -> failwith "Shoot"
}
Async.StartImmediate(playMode playModeObservables sudokuGame 0) ; System.Windows.Forms.Application.Run(form)
答案 0 :(得分:0)
感谢@johnpalmer向我展示了this网站,并且因为来自this site和@fyodorsoikin的一个例子(他指出了正确的方法),我能够解决这个问题。
要获取密钥,您需要一个KeyEventHandler,它需要一个在敲击密钥时调用的函数。在此功能中,您可以检查其他内容并执行您需要执行的操作。
例如:
let stuffToDoWhenKeyPressed s (e : KeyEventArgs) =
match e with
| e when e.KeyCode = Keys.D0 -> gameButtons.[0].Text <- "0"
| e when e.KeyCode = Keys.D1 -> gameButtons.[0].Text <- "1"
| _ -> GUI.Play.gameButtons.[0].Text <- "?"
gameButtons.[0].KeyDown.AddHandler(new System.Windows.Forms.KeyEventHandler (fun s e -> stuffToDoWhenKeyPressed s e ))