Search code examples
c#system.windows.media

Drawing a rectangle but the color of the pen will not work


The error is on the line after //Create pen. It states that System.Windows.Media.Color does not contain a definition for 'Black'. How do I fix this?

   public void DrawRectangleRectangle(PaintEventArgs e)
    {

        // Create pen.
        System.Windows.Media.Pen blackPen = new System.Windows.Media.Pen(Color.Black, 3);

        // Create rectangle.
        System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, 200, 200);

        // Draw rectangle to screen.
        e.Graphics.DrawRectangle(blackPen, rect);
    }

How about this, and going back to scratch:

    public void DrawRectangleRectangle(PaintEventArgs e)
    {

        // Create pen.
        Pen blackPen = new Pen(Color.Black, 3);

        // Create rectangle.
        Rectangle rect = new Rectangle(0, 0, 200, 200);

        // Draw rectangle to screen.
        e.Graphics.DrawRectangle(blackPen, rect);
    }

There is an error on Black saying System.Windows.Media has no definition for 'Black'. I got this example from Graphics.DrawRectangle

How do I adapt it to my code?


Solution

  • For a winforms application, you should be using classes from the System.Drawing namespace; e.g. System.Drawing.Pen.

    The System.Windows.Media namespace contains classes for WPF applications.

    I suggest you put using System.Drawing at the top of your file (and remove using System.Windows.Media), and then simply use Pen and Rectangle in your code.