Per the comment in the exercise reminding us that we had already written a colorsamples selector in an earlier lesson, I wrote a version of the above exercise by adding a reference to the earlier project rather than copy and past it. This code is not perfect but I thought I would share it.
I made the sampleColorLabel public and encapsulated the code to call the dialog in a helper method which references the Namespace of the previous project.
Code:
//Current foreground or background color passed in.
private Color displayDialog(Color color)
{
ColorSamples.ColorSamples colorSamplesDialog;
colorSamplesDialog = new ColorSamples.ColorSamples();
if (colorSamplesDialog.ShowDialog() == DialogResult.OK)
{
//If OK is selected return the new color
return colorSamplesDialog.sampleLabel.BackColor;
}
else
{
//otherwise return the same color passed in (no change in color).
return color;
}
}
I then call this helper method from each of the buttons:
Code:
private void foreColorButton_Click(object sender, EventArgs e)
{
//Call dialog. OK: new color
//Cancel: return the current ForeColor, resulting in no change.
this.ForeColor = displayDialog(this.ForeColor);
}
private void backColorButton_Click(object sender, EventArgs e)
{
//Call dialog. OK: new color
//Cancel: return the current ForeColor, resulting in no change.
this.BackColor = displayDialog(this.BackColor);
}
}