3

I'm implementing a gameboy emulator as so many before me.

I'm trying to implement the PPU and to do this I'm using a class representing the screen.

// needed because VS can't find it as dependency
#r "nuget: System.Windows.Forms"
open System
open System.Windows.Forms
open System.Drawing

type Screen(title, width : int, height : int) as screen =
    inherit Form()
    
    let mutable canvas = new Bitmap(width, height)

    do
        // set some attributes of the screen
        screen.Size <- new Size(width, height)
        screen.Text <- title

    interface IDisposable with
        member S.Dispose() = (canvas :> IDisposable).Dispose()

    override S.OnPaint e =
        e.Graphics.DrawImage(canvas,0,0) // here
        base.OnPaint(e)

    member S.Item
        with get (w, h) = canvas.GetPixel(w,h)
        and set (w,h) pixel = canvas.SetPixel(w,h,pixel)

But I can't get it to update the screen after I have redrawing the bitmap, it does not show the redrawn image.

the redraw

let main () =
    let screen = new Screen("gameboy",800,600)
    Application.Run(screen)
    // test example
    for i in 0 .. 300 do
        screen.[i,i] <- Drawing.Color.Black
    (screen :> Form).Refresh()

i.e. How do I make it to redraw after update of the bitmap?

kam
  • 590
  • 2
  • 11

1 Answers1

4

You can't do anything graphical after Application.Run has been called, because it doesn't finish until the user closes the main form. Instead, you can create an event handler that is called once the main form is loaded, like this:

let main argv =
    let screen = new Screen("gameboy",800,600)
    screen.Load.Add(fun _ ->
        for i in 0 .. 300 do
            screen.[i,i] <- Drawing.Color.Black)
    Application.Run(screen)
    0
Brian Berns
  • 15,499
  • 2
  • 30
  • 40
  • Thanks. where should I put the screen refresh/invalidate call to make it redraw? – kam Feb 23 '21 at 09:20
  • If you want to do animation, you probably want to create a timer, and then invalidate inside the timer's event handler. [This SO question](https://stackoverflow.com/questions/188349/simple-animation-using-c-windows-forms) has useful details. – Brian Berns Feb 23 '21 at 15:41