I found this answer for Python here Question/Answer. I wanted to know how I could do this in F# and what specifically do I need to import and how do I get the device context. I realize it's better to use a window but I don't want too for the project I'm working on. I'm guessing there is a way to get the width/height of the screen too.
Asked
Active
Viewed 361 times
1 Answers
3
Here is a minimal example that uses the GetDC
and SetPixel
functions to do exactly the same thing as the Python example in the referenced question:
open System
open System.Runtime.InteropServices
[<DllImport("user32.dll",EntryPoint="GetDC")>]
extern IntPtr GetDC(IntPtr ptr)
[<DllImport("gdi32.dll")>]
extern uint32 SetPixel(IntPtr hdc, int X, int Y, uint32 crColor);
let dc = GetDC(IntPtr.Zero)
for i in 0 .. 255 do
let r, g, b = 255, i, 255
let clr = (r <<< 16) ||| (g <<< 8) ||| b
SetPixel(dc, i, 0, uint32 clr) |> ignore
That said, I cannot imagine a scenario where this would be a good thing to do. If you are creating a sensible windows application, you will most certainly want to draw anything in the window belonging to your app.

Tomas Petricek
- 240,744
- 19
- 378
- 553
-
1A screenshot application where a frame is drawn for selecting just part of the screen could be a case where you don't want an additional window. – Markus Deibel Jan 13 '19 at 09:55
-
@Tomas Petricek Do you know how to keep the drawing open after setting the pixels? It disappears after I move my cursor. Sorry, I know this is an old post. – Sep 20 '19 at 13:47
-
@Alanay I don't know - it's probably best to open a new question! (This one is 7 years old :-)) I guess that to keep the pixels, you might need a window. – Tomas Petricek Sep 20 '19 at 14:12
-
I'll search a bit more, if I can't find an answer I'll open a new question. :P – Sep 20 '19 at 14:16