每秒更新winforms Paint.Add

时间:2018-01-23 10:13:23

标签: winforms f#

我正在尝试使用秒计数器制作一个小应用程序,该计数器每秒顺时针旋转一圈。我已经找到了许多部分,但是无法按照我的意愿每秒更新一行。我在下面粘贴了一个MWE,只需将手旋转90度。我希望它每秒旋转360/60 * s(其中s是当前秒)。

我已经尝试了一些定时器对象的东西(见底部的行),但没有一个有帮助。任何帮助将不胜感激。

open System.Windows.Forms
open System.Drawing

// Prepare window form
let win = new System.Windows.Forms.Form ()
// Set some properties
win.BackColor <- System.Drawing.Color.White
let height = 250
let width = 200
win.Size <- System.Drawing.Size (width, height)

// make a timer 
let timer = new Timer ()
timer.Interval <- 1000 // create an event every 1000 millisecond 
timer.Enabled <- true // activate the timer

let getEndPoint degrees =
  let t = float 50
  let s = float 0
  let theta = float degrees * (System.Math.PI / float 180)
  let u = (s * (cos theta) + t * (sin theta)) + float 100
  let v = (-s * (sin theta) + -t * (cos theta)) + float 100
  Point (int u,int v)

// Set paint call-back function
let paint (e : PaintEventArgs) (x) : unit = 
    let pen = new Pen (Color.Black)
    let endPoint = getEndPoint x
    let points = [|Point (100,100); endPoint|] 
    e.Graphics.DrawLines (pen, points)

let getDegrees =
  360/60*System.DateTime.Now.Second

let addPaint degrees =
  printfn "Draws with degrees %A" degrees
  win.Paint.Add (fun e -> (paint e degrees))

win.Paint.Add (fun e -> (paint e 90))
//timer.Tick.Add (fun e -> (addPaint 90)) // Doesn't draw
//timer.Tick.Add (fun e -> (addPaint getDegrees)) // Doesn't draw, updates every second, but doesn't change degrees 
//timer.Tick.Add (fun e -> (addPaint (360/60*System.DateTime.Now.Second))) // Doesn't draw, but get correct degrees 

// Start the event-loop.
System.Windows.Forms.Application.Run win

1 个答案:

答案 0 :(得分:2)

使用以下两行解决了这个问题:

win.Paint.Add (fun e -> (paint e (360/60*System.DateTime.Now.Second)))
timer.Tick.Add (fun e -> win.Invalidate())