Home > Back-end >  How to make colordialog appear?
How to make colordialog appear?

Time:12-20

I am simply trying to make a colordialog appear, using the following code as a test out/practise assignment.

{
            Point puntA = new Point(10, 300);
            Point puntB = new Point(90, 200);
         
            Pen tekenpotlood = new Pen(colorDialog1.Color , 4);

            Graphics papier = pictureBox1.CreateGraphics();

            papier.DrawLine(tekenpotlood, puntA, puntB);

}

I have dragged a colordialog onto the form, I have also added the code menntioned in the textbook (with or without erasing colordialog)

any help is appreaciated with this problem..

CodePudding user response:

To use a ColorDialog in your C# code, you need to do the following:

Declare a ColorDialog variable at the class level:

public class Form1 : Form
{
    ColorDialog colorDialog;
    
    // Other class members and constructor
}
Initialize the ColorDialog variable in the form's constructor or in a separate method:
public Form1()
{
    colorDialog = new ColorDialog();
}
To show the ColorDialog to the user and get the selected color, call the ShowDialog() method on the ColorDialog object and check the DialogResult:

    if (colorDialog.ShowDialog() == DialogResult.OK)
    {
        // The user selected a color and clicked OK
        // Use the colorDialog.Color property to get the selected color
    }
    else
    {
        // The user cancelled the dialog
    }
    Use the selected color to set the color of the Pen object:
    
        Pen pen = new Pen(colorDialog.Color, 4);
        Point puntA = new Point(10, 300);
        Point puntB = new Point(90, 200);
        
        if (colorDialog.ShowDialog() == DialogResult.OK)
        {
            Pen pen = new Pen(colorDialog.Color, 4);
        
            Graphics papier = pictureBox1.CreateGraphics();
        
            papier.DrawLine(pen, puntA, puntB);
        }

CodePudding user response:

Thanks a lot for the answer, Classes is the next chapter of the course, but i got it to work, with some changes.

here is the code now functioning:

public partial class Form1 : Form
{
    ColorDialog colorDialog;

    public Form1()
    {
        colorDialog = new ColorDialog();
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
       





    Pen pen = new Pen(colorDialog.Color, 4);
    Point puntA = new Point(10, 300);
    Point puntB = new Point(90, 200);
    
    if (colorDialog.ShowDialog() == DialogResult.OK)
    {
       

    Graphics papier = pictureBox1.CreateGraphics();

    papier.DrawLine(pen, puntA, puntB);
    }

        else
        {
            // The user cancelled the dialog
        }


    }
}

}

  • Related