1

Let's say I have a VB.net or C# console program that outputs its data to console. Is there a way to change color of a pixel? For example, my resolution is 1600x900. Can I paint pixel (800,600) red? Can I do the same for the active window (paint pixel (300,300) if the console is 400x400 - using coordinates relative to console)? What i want to do is to make a plot of some expression. I have multiple points and their coordinates and i want to draw them in the console by painting pixels. I'm really puzzled how to do this. Any suggestion and help is very much appreciated.

Dobrobobr
  • 7,476
  • 4
  • 15
  • 18

3 Answers3

0

You can change the Foreground and Background color as you write to the Console, but that's it. You need to use Winforms to accomplish what you want.

Jeff
  • 908
  • 2
  • 9
  • 23
0

You cant draw a pixels, but you can use colored pseudographics. You can use Win32 functions like WriteConsoleOutput by p/invoking them. See Advanced Console IO in .NET for example.

Community
  • 1
  • 1
0

I know this answer is a little late, but in case you still want it, need it, or if someone else wants it, I found some tutorials and other things on stack overflow that led me to an answer. Here it is:

 [DllImport("kernel32.dll", EntryPoint = "GetConsoleWindow", SetLastError = true)]
    private static extern IntPtr GetConsoleHandle();

    IntPtr handler;
    Bitmap mainMap;

    void FinalDraw()
    {
        using (var graphics = Graphics.FromHwnd(handler))
            graphics.DrawImage(mainMap, new PointF(0, 0));
    }

Now just change the pixels inside the Bitmap mainMap, using mainMap.SetPixel(Color), and your all set, just call FinalDraw, and there you go. You will need to set mainMap to a new Bitmap and set the resolution. Finally make sure to install the System.Drawing.Common from the Manage NuGet window in Visual Studios. As well as add using System.Drawing; You may need to add a project reference as well. Good luck and have fun!

Edit:

Youll need to include System.Drawing, and System.Runtime.InteropServices. THe System.Drawing is for the graphics object, and the InteropServices is for the dll imports.

You can also make a reference to a graphics object, so you don't need to constantly use using.

So instead probably create a class that stores all your functions and the graphics object.

Example:

public class Canvas
{

    [DllImport("kernel32.dll", EntryPoint = "GetConsoleWindow", 
SetLastError = true)]
        private static extern IntPtr GetConsoleHandle();

        IntPtr handler;
    Graphics g;

    public Canvas()
    {
        using(var graphics = Graphics.FromHwnd(handler))
            g = graphics;
    }
}