I have put in code to change the MSCharting area colour when printing.
chart.ChartAreas[o].BackColor = System.Drawing.Color.White;
chart.Printing.PrintPreview();
My quesiton is, how can I handle the color to change back to its oringinal color, eitehr after user has selected Print, or Close form the printpreview dialog,, or if the click on the dialogs "X".
In fact if I use the PrintDialog instead, how could I set background back to normal once printing has been completed or canceled?
little late but I hope it helps someone.
To MsChart print I'am using PrintDocument events. BeginPrint event for setting colors for printing, PrintPage event for print itself and EndPrint event for setting colors back before print.
Sample code:
public GraphFrm()
{
InitializeComponent();
//new PrintDocument object to reset default one
chart.Printing.PrintDocument = new System.Drawing.Printing.PrintDocument();
//set up events
chart.Printing.PrintDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(PrintDocument_PrintPage);
chart.Printing.PrintDocument.BeginPrint +=new System.Drawing.Printing.PrintEventHandler(PrintDocument_BeginPrint);
chart.Printing.PrintDocument.EndPrint += new System.Drawing.Printing.PrintEventHandler(PrintDocument_EndPrint);
//default print setting like margins and landscape
chart.Printing.PrintDocument.DefaultPageSettings.Margins.Bottom = 50;
chart.Printing.PrintDocument.DefaultPageSettings.Margins.Top = 50;
chart.Printing.PrintDocument.DefaultPageSettings.Margins.Left = 50;
chart.Printing.PrintDocument.DefaultPageSettings.Margins.Right = 50;
chart.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
chart.Printing.PrintDocument.DefaultPageSettings.Color = true;
...
}
public void Print()
{
//print method with show print dialog
chart.Printing.Print(true);
}
void PrintDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
//set print color
PrintChartColorSet();
}
void PrintDocument_EndPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
//restore colors
PrintChartColorRestoreDefault();
}
void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//print chart into rectangle defined by margins
Rectangle chartPosition = new Rectangle(e.MarginBounds.X, e.MarginBounds.Y, e.MarginBounds.Width, e.MarginBounds.Height);
chart.Printing.PrintPaint(e.Graphics, chartPosition);
}
Color BackColor, BorderlineColor, CaBackColor, CaBorderColor, AxColor, LeBackColor, LeForeColor;
void PrintChartColorSet()
{
BackColor = chart.BackColor;
chart.BackColor = Color.White;
BorderlineColor = chart.BorderlineColor;
chart.BorderlineColor = Color.White;
CaBackColor = chart.ChartAreas[0].BackColor;
chart.ChartAreas[0].BackColor = Color.White;
CaBorderColor = chart.ChartAreas[0].BorderColor;
chart.ChartAreas[0].BorderColor = Color.Black;
AxColor = chart.ChartAreas[0].Axes[0].LineColor;
foreach(Axis a in chart.ChartAreas[0].Axes)
{
a.LineColor = Color.Black;
a.TitleForeColor = Color.Black;
a.MajorGrid.LineColor = Color.Black;
a.MajorTickMark.LineColor = Color.Black;
a.MinorGrid.LineColor = Color.Black;
a.MinorTickMark.LineColor = Color.Black;
a.LabelStyle.ForeColor = Color.Black;
}
LeBackColor = chart.Legends[0].BackColor;
chart.Legends[0].BackColor = Color.White;
LeForeColor = chart.Legends[0].ForeColor;
chart.Legends[0].ForeColor = Color.Black;
}
void PrintChartColorRestoreDefault()
{
chart.BackColor = BackColor;
chart.BorderlineColor = BorderlineColor;
chart.ChartAreas[0].BackColor = CaBackColor;
chart.ChartAreas[0].BorderColor = CaBorderColor;
foreach(Axis a in chart.ChartAreas[0].Axes)
{
a.LineColor = AxColor;
a.TitleForeColor = AxColor;
a.MajorGrid.LineColor = AxColor;
a.MajorTickMark.LineColor = AxColor;
a.MinorGrid.LineColor = AxColor;
a.MinorTickMark.LineColor = AxColor;
a.LabelStyle.ForeColor = AxColor;
}
chart.Legends[0].BackColor = LeBackColor;
chart.Legends[0].ForeColor = LeForeColor;
}
Unfortunatly there is no easy way since PrintPreview doesnt provide any callbacks.
You can make a copy of the chart used solely for printing with the default chart area replaced by your custom area (with custom background).
Another way is to change the BG Color, print the chart to a in-memory image using PrintPaint, restore the BG Color and show a print dialog manually for the image you just rendered.
There are more ways like hooking the newly created window but they are getting more complex and more dirty.
Good luck
Related
I want to include the colored panel below into my form:
For this I have created custom panel which will change Border color based on Radio Button selection. My panel code is
InfoPanel.cs
class InfoPanel : Panel
{
private Color colorBorder = Color.Transparent;
public InfoPanel()
: base()
{
this.SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawRectangle(
new Pen(
new SolidBrush(colorBorder), 2),
e.ClipRectangle);
e.Graphics.DrawLine(new Pen(new SolidBrush(colorBorder), 0), 50, 0, 50, 50); //drawing a line to split the child & parent info panel
}
public Color BorderColor
{
get
{
return colorBorder;
}
set
{
colorBorder = value;
}
}
}
In my form,
1. created one parent Info Panel
2. created one child panel with Picture box
3. One label in parent info panel to show the information
Now for the parent panel I am changing the colors [back, border] & text based on user selection & for child panel I am not changing border color but updating back color based on user selection.
Below is the code for changing the panel colors, image, text update:
private void rbIPAddress_CheckedChanged(object sender, EventArgs e)
{
if (rbIPAddress.Checked)
{
ParentInfoPanel.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFEE");
ParentInfoPanel.BorderColor = System.Drawing.ColorTranslator.FromHtml("#DADA85");
ChildInfoPanel.BackColor = System.Drawing.ColorTranslator.FromHtml("#F6F6D8");
InfoPanelPictureBox.Image = Template.InfoPanelInfoImage;
Infolabel.Text = "IP Address is already configured. You can switch to Forward Lookup Zone by choosing other configuration. *IP Address \ncan be either LB IP Address.";
txtBoxIPAddress.Enabled = true;
textBoxPort.Enabled = true;
}
else
{
Infolabel.Text = "";
txtBoxIPAddress.Text = "";
txtBoxIPAddress.Enabled = false;
textBoxPort.Enabled = false;
}
}
private void rbForwardLookupZone_CheckedChanged(object sender, EventArgs e)
{
if (rbForwardLookupZone.Checked)
{
ParentInfoPanel.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFEE");
ParentInfoPanel.BorderColor = System.Drawing.ColorTranslator.FromHtml("#DADA85");
ChildInfoPanel.BackColor = System.Drawing.ColorTranslator.FromHtml("#F6F6D8");
InfoPanelPictureBox.Image = Template.InfoPanelInfoImage;
Infolabel.Text = "Forward Lookup Zone is already configured. You can switch to IP Address by choosing other configuration and \nchanging port number will affect Firewall rules.";
textBoxControlPlane.Enabled = true;
if (string.IsNullOrEmpty(textBoxControlPlane.Text))
{
textBoxControlPlane.Text = Constants.DefaultControlPlaneDomain;
}
}
else
{
Infolabel.Text = "";
textBoxControlPlane.Text = "";
textBoxControlPlane.Enabled = false;
}
}
Note: used next line character to display label text in multiple line
Output: Everything is ok but in the end of label text I am getting another rectangle box. I'm wondering why is showing like this? Am I doing wrong? Please help me on this.
The issue is that you're using e.ClipRectangle. It informs you which portion of the control needs to be redrawn. This is sometimes only a small part of the control rather than the whole thing (in your case the area of the extra rectangle). Always draw the control's full rectangle instead.
Also, you must dispose of both the Pen and SolidBrush. Failing to do so causes memory leaks. Utilize the using statement.
using(SolidBrush brush = new SolidBrush(colorBorder))
using(Pen pen = new Pen(brush, 2))
{
e.Graphics.DrawRectangle(pen, new Rectangle(0, 0, this.ClientSize.Width - 1, this.ClientSize.Height - 1));
e.Graphics.DrawLine(pen, 50, 0, 50, 50);
}
I am displaying a transparent icon (32x32) of a red triangle in the upper right of a button control that signifies an error exists. Additionally, when the user hovers over the icon, a tool tip is displayed.
I have been able to display the icon and the associated tool tip. The problem is a transparent 32x32 icon with the red triangle being only 12x12. The tool tip should only trigger when hovering over the red triangle and not the transparent space.
Attempts have been made to display the triangle as a button as well as a picture box, however the tool tip still triggers in the transparent space. Additionally, the error provider was first used as a goal of what I am trying to accomplish.
UI items:
Button control: "btnAttachments"
Error Provider control: "errManager"
public class StackTest
{
private static Dictionary<string, Control> _errorMessages = new Dictionary<string, Control>();
public StackTest()
{
InitializeComponent();
InitErrors();
}
private void InitErrors()
{
_errorMessages.Clear();
AddErrorControl(btnAttachments, "Missing file attachment(s).");
//errManager.SetError(btnAttachments, "Missing file attachment(s)."); errManager.SetIconPadding(btnAttachments, -32);
}
private void AddErrorControl(Control control, string message = null, Enum selectedImage = null, EventHandler handler = null)
{
string name = "errFor" + control.Name;
if (_errorMessages.ContainsKey(name)) { return; }
Button errorIcon = CreateErrorControl(name, control);
errorIcon.BackgroundImage = Theme.GetImage(selectedImage ?? eImages_OtherIcons.Error_TopRight_Small);
//PictureBox errorIcon = CreateErrorControl2(name);
//errorIcon.Image = Theme.GetImage(selectedImage ?? eImages_OtherIcons.Error_TopRight_Small);
//errorIcon.Image = Bitmap.FromHicon((Theme.GetIcon(selectedImage ?? eImages_OtherIcons.Error_TopRight_Small)).Handle);
if (null != handler) { errorIcon.Click += handler; }
new ToolTip().SetToolTip(errorIcon, message);
errorIcon.Tag = message;
control.Controls.Add(errorIcon);
control.Controls[name].Location = new Point(control.Width - errorIcon.Width +20 , 0 );
_errorMessages.Add(name, errorIcon);
}
private Button CreateErrorControl(string name, Control control)
{
var errorIcon = new Button();
errorIcon.Name = name;
errorIcon.Size = new Size(32, 32);
//errorIcon.Location = new Point(control.Width - errorIcon.Width, 0);
errorIcon.Cursor = Cursors.Hand;
errorIcon.FlatStyle = FlatStyle.Flat;
errorIcon.BackColor = Color.Fuchsia;
errorIcon.FlatAppearance.MouseDownBackColor = Color.Transparent;
errorIcon.FlatAppearance.MouseOverBackColor = Color.Transparent;
errorIcon.FlatAppearance.BorderSize = 0;
errorIcon.Visible = false;
return errorIcon;
}
private PictureBox CreateErrorControl2(string name)
{
var errorIcon = new PictureBox();
errorIcon.Name = name;
errorIcon.Size = new Size(32, 32);
errorIcon.Cursor = Cursors.Hand;
errorIcon.BackColor = Color.Transparent;
errorIcon.Visible = false;
return errorIcon;
}
}
The built in Error Provider control achieves the desire results that I would like to replicate. Doing so will allow for a more robust application with more custom functionality then what the error provider offers.
Based on the GetPixel suggestion from #TaW, I did further R&D and now have something functional. The Tag of the picture box contains the tool tip message to be displayed. With the picture box being the "sender" of the mouse move, it was easy to extract the image back to a bitmap.
Thanks to all for the feedback.
First, I switched the testing to use CreateErrorControl2 with the PictureBox and added in a MouseMove.
private PictureBox CreateErrorControl2(string name) //, Control control)
{
var errorIcon = new PictureBox();
errorIcon.Name = name;
errorIcon.Size = new Size(32, 32);
errorIcon.Cursor = Cursors.Default;
errorIcon.BackColor = Color.Transparent;
errorIcon.Visible = false;
errorIcon.MouseMove += new MouseEventHandler(DisplayToolTip);
return errorIcon;
}
The following code was also added in support of the DisplayToolTip method.
private bool _toolTipShown = false;
private bool IsTransparent(PictureBox pb, MouseEventArgs e)
{
Color pixel = ((Bitmap)pb.Image).GetPixel(e.X, e.Y);
return (0 == pixel.A && 0 == pixel.R && 0 == pixel.G && 0 == pixel.B);
}
private void DisplayToolTip(object sender, MouseEventArgs e)
{
Control control = (Control)sender;
IsTransparent((PictureBox)control, e);
if (IsTransparent((PictureBox)control, e))
{
_toolTip.Hide(control);
_toolTipShown = false;
}
else
{
if (!_toolTipShown)
{
_toolTip.Show(control.Tag.ToString(), control);
_toolTipShown = true;
}
}
}
i want coloring each box(not text items) in combobox which have different items, example: mountain have it's box red, sea have it's box blue, etc. i've tried but it's really jumbled bunch of color which i've tried
i need to highlight every combobox items to show it's intended color, when clicking that combobox it's not showing its intended color
code below
private void cmbRegion_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
string text = ((ComboBox)sender).Items[e.Index].ToString();
Brush brush;
if (text.Equals("Mountain"))
{
brush = Brushes.Black;
cmbRegion.BackColor = Color.Red;
}
else if (text.Equals("Sea"))
{
brush = Brushes.Black;
cmbRegion.BackColor = Color.Blue;
}
else
{
brush = Brushes.Black;
cmbRegion.BackColor = Color.White;
}
// Draw the text
e.Graphics.DrawString(text, ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y);
}
can it be done..?
Modified MSDN example to match your requirement. The important property here is the DrawMode.
private void Form1_Load(object sender, EventArgs e)
{
InitializeComboBox();
}
internal ComboBox ComboBox1;
private string[] items;
// This method initializes the owner-drawn combo box.
// The drop-down width is set much wider than the size of the combo box
// to accomodate the large items in the list. The drop-down style is set to
// ComboBox.DropDown, which requires the user to click on the arrow to
// see the list.
private void InitializeComboBox()
{
this.ComboBox1 = new ComboBox();
this.ComboBox1.DrawMode =
System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.ComboBox1.BackColor = Color.Red;
this.ComboBox1.Location = new System.Drawing.Point(10, 20);
this.ComboBox1.Name = "ComboBox1";
this.ComboBox1.Size = new System.Drawing.Size(100, 120);
this.ComboBox1.DropDownWidth = 250;
this.ComboBox1.TabIndex = 0;
this.ComboBox1.DropDownStyle = ComboBoxStyle.DropDown;
items = new string[] { "Mountain", "Sea", "Other" };
ComboBox1.DataSource = items;
this.Controls.Add(this.ComboBox1);
// Hook up the MeasureItem and DrawItem events
this.ComboBox1.DrawItem +=
new DrawItemEventHandler(ComboBox1_DrawItem);
this.ComboBox1.MeasureItem +=
new MeasureItemEventHandler(ComboBox1_MeasureItem);
this.ComboBox1.SelectedIndexChanged += ComboBox1_SelectedIndexChanged;
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Color itemBackgroundColor = new Color();
switch (ComboBox1.SelectedIndex)
{
case 0:
itemBackgroundColor = Color.Red;
break;
case 1:
itemBackgroundColor = Color.Blue;
break;
case 2:
itemBackgroundColor = Color.Green;
break;
}
ComboBox1.BackColor = itemBackgroundColor;
}
// If you set the Draw property to DrawMode.OwnerDrawVariable,
// you must handle the MeasureItem event. This event handler
private void ComboBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
// No change to item height.
e.ItemHeight = e.ItemHeight;
}
// You must handle the DrawItem event for owner-drawn combo boxes.
// This event handler changes the color, size and font of an
// item based on its position in the array.
private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
string text = ((ComboBox)sender).Items[e.Index].ToString();
Color itemBackgroundColor = new Color();
switch (e.Index)
{
case 0:
itemBackgroundColor = Color.Red;
break;
case 1:
itemBackgroundColor = Color.Blue;
break;
case 2:
itemBackgroundColor = Color.Green;
break;
}
// Draw the background of the item.
e.DrawBackground();
// Create a square filled with the animals color. Vary the size
// of the rectangle based on the length of the animals name.
e.Graphics.FillRectangle(new SolidBrush(itemBackgroundColor), e.Bounds);
// Draw each string in the array, using a different size, color,
// and font for each item.
e.Graphics.DrawString(items[e.Index], e.Font, Brushes.Black, e.Bounds);
// Draw the focus rectangle if the mouse hovers over an item.
e.DrawFocusRectangle();
}
I've been experimenting with adding elements to Windows Forms dynamically via code.
I need to create a PictureBox element. So, far, I have the following code:
private void Form1_Load(object sender, EventArgs e)
{
//stylise form
this.BackColor = System.Drawing.Color.Black;
PictureBox bgui = new PictureBox();
bgui.Image = Properties.Resources.attack_box;
bgui.Name = "bgui";
bgui.Location = new Point(0, 600);
this.Controls.Add(bgui);
bgui.Visible = true;
}
However, when this code is run, I get nothing but the black background which I set earlier. I've looked at many questions similar to mine; and they all say I need to add it to the control, which I have done, yet it still abstains from showing.
I would really appreciate it if you could give me an insight into my wrong-doing.
Thanks, Computo.
You need to set Width and Height Properties of the PictureBox.
Try This:
bgui.Width = 500;
bgui.Height = 500;
Complete Code:
private void Form1_Load(object sender, EventArgs e)
{
//stylise form
this.BackColor = System.Drawing.Color.Black;
PictureBox bgui = new PictureBox();
bgui.Image = Properties.Resources.attack_box;
bgui.Name = "bgui";
bgui.Width = 500;
bgui.Height = 500;
bgui.Location = new Point(0, 600);
this.Controls.Add(bgui);
bgui.Visible = true;
}
Turns out that System.Drawing.Point does not translate to the actual pixels on the screen. I will have to investigate how Point translates into pixels.
Here its works perfect. Specify the SizeMode and change the location.
private void Form1_Load(object sender, EventArgs e)
{
//stylise form
this.BackColor = System.Drawing.Color.Black;
PictureBox bgui = new PictureBox();
bgui.Image = Properties.Resources.attack_box;
bgui.Location = new System.Drawing.Point(100, 0);
bgui.Name = "pictureBox1";
bgui.SizeMode = PictureBoxSizeMode.AutoSize;
this.Controls.Add(bgui);
}
I'm working with .NET forms in Visual C#.
I've created a label dynamically, which shows upon a button click. This all works fine; what I'm trying to do is position it so that the element is at the centre of the form. Normally, I'd just set it to half the form size, minus half the element size, but of course this won't work as I am setting the text programmatically also.
My code for the label is as follows:
if(part == 1){
theLabel.Text = "Choose a name for your character!";
}
theLabel.ForeColor = Color.DarkGray;
theLabel.Font = new Font("Arial", 14, FontStyle.Bold);
theLabel.Location = new Point();
I've tried many things here, but I just cannot think of a way. I've tried int[] sizes = (int)theLabel.Size and various other but I just cannot get this to work. Is there another way to line this element to the middle?
If I was you I'd do it this way.
Label theLabel;
private void button1_Click(object sender, EventArgs e)
{
theLabel = new Label();
theLabel.AutoSize = true;
theLabel.BackColor = Color.Red;
theLabel.TextAlign = ContentAlignment.MiddleCenter;
theLabel.Text = "Choose a name for your character!";
this.Controls.Add(this.theLabel);
theLabel.Left = (this.ClientRectangle.Width - theLabel.Width) / 2;
//theLabel.ForeColor = Color.Black;
theLabel.Top = 25;
theLabel.Show();
}