Is there anyway of getting all of the properties of a !enabled textbox except the faded text?
I cannot use a Label because I want the textbox to be enabled eventually. I cannot use readonly because I do not want the user's cursor to appear within.
It would be best to have both a Label and a TextBox in the same location.
Hide the TextBox and display the content in a Label until you are ready to edit it.
At that point, hide the Label and show the TextBox.
Otherwise you'll have to subclass the TextBox, and override the OnPaint method, somewhat like the following:
protected override void OnPaint(PaintEventArgs e)
{
SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
// Draw string to screen.
e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property
}
Take a look at this answer and this link.
Use a SystemColor instead of KnownColor:
Color color = textbox1.BackColor ;
textbox1.BackColor = System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);
color = textbox1.ForeColor ;
textbox1.ForeColor = System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);
Related
I have created a ListBox to which I add elements during code compilation. and I want to record its color when adding one element (so that each added element has a different color)
listBox1.Items.Add(string.Format("Місце {0} | В роботі з {1} | ({2} хв)", temp[7].Substring(6, 4), temp[8].Substring(11, 5), rezult)); `
I tried everywhere possible to embed this change
BackColor = Color.Yellow;ForeColor = Color.Yellow;
I am working with listbox because I have seen so many answers about ListView.
Set the listbox DrawMode to either OwnerDrawFixed or OwnerDrawVariable and set this as the DrawItem event handler:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e){
if(e.Index == 1) e.DrawBackground(); //use e.Index to see if we want to highlight the item
else e.Graphics.FillRectangle(new SolidBrush(Color.Yellow), e.Bounds); //This does the same thing as e.DrawBackground but with a custom color
e.DrawFocusRectangle();
if(e.Index < 0) return;
TextRenderer.DrawText(e.Graphics, (string)listBox1.Items[e.Index], listBox1.Font, e.Bounds, listBox1.ForeColor, TextFormatFlags.Left);
}
Well, best idea I have is to not use list box, but flowLayoutPanel and add usercontrols where you will have labels.
flowLayoutPanel works as list of controls which you can scroll, so we will just create a usercontrol, where we will put label and change the usercontrol background
Don't forget to turn on the AutoScroll feature to flowLayoutPanel, otherwise the scroll bar wont work and wont even show up.
If you want to be able to be clickable just add to the label click event.
public void CreateItem(Color OurColor, string TextToShow)
{
Label OurText = new Label()
{
Text = "TextToShow",
Font = new Font("Segoe UI", 8f),
Location = new Point(0, 0),
AutoSize = true,
};
UserControl OurUserControl = new UserControl();
OurUserControl.Size = new Size((int)((double)flowLayoutPanel1.Width * 0.9) , OurText.Font.Height);
OurUserControl.BackColor = OurColor;
OurUserControl.Controls.Add(OurText);
flowLayoutPanel1.Controls.Add(OurUserControl);
}
I am setting the ForeColor of all items in my ListView to a different color, but this get's overrided when the item is selected (changes to Black again; changes back to custom color on deselection).
I want my items to retain my custom color, even in selection.
I'm basically asking the same question that was asked here 7 years ago, and doesn't seem to have any satisfactory answer.
I tried searching in SO and elsewhere, and no luck. The only solution provided so far is to draw the whole thing (the DrawItem method), which I gave a try but is ridiculously complicated for such a petty requirement...
Is this the only way? Say it ain't so.
Enable your ListView OwnerDraw mode, then subscribe its DrawItem and DrawColumnHeader events.
If your design requires it, also subcribe the DrawSubitem event.
At this point, you can draw anything in the related areas of your ListView.
In the example, I've painted a little symbol in the Header area.
The Header text needs to be painted too.
If the Background color doesn't change (same as in design mode), you just need to use the DrawListViewItemEventArgs e parameter function e.DrawBackground();
If not, use e.Graphics.FillRectangle() to color the Item area, defined by e.Bounds.
The Item Text is drawn using e.Graphics.DrawString().
The item Text is e.Item.Text, the text area is defined by e.Bounds again.
If you don't need any specific details/settings for the item's text, you can simply use e.DrawText();, which uses the default properties (defined at design-time).
Here, the item color complex logic is that the color is specified inside the item text. Could be anything else. The item tag, its Index position, a List<Parameters>, you name it.
This is how it might look like:
(I added e.Graphics.TextRenderingHint = [] to show how you can control the quality of the rendered text. e.Graphics.TextContrast can be also used to enhance the contrast).
Note: this code sample only draws a generic image, if the ListView has an ImageList. You should also verify whether the SmallIcon/LargeIcon ImageLists are defined and draw the related Image in the specified size. It's the same procedure, though.
protected void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
e.Item.UseItemStyleForSubItems = true;
int imageOffset = 0;
Rectangle rect = e.Item.Bounds;
bool drawImage = !(e.Item.ImageList is null);
Color itemColor = Color.FromName(e.Item.Text.Substring(e.Item.Text.LastIndexOf(" ") + 1));
using (var format = new StringFormat(StringFormatFlags.FitBlackBox)) {
format.LineAlignment = StringAlignment.Center;
if (drawImage) {
imageOffset = e.Item.ImageList.ImageSize.Width + 1;
rect.Location = new Point(e.Bounds.X + imageOffset, e.Item.Bounds.Y);
rect.Size = new Size(e.Bounds.Width - imageOffset, e.Item.Bounds.Height);
e.Graphics.DrawImage(e.Item.ImageList.Images[e.Item.ImageIndex], e.Bounds.Location);
}
if (e.Item.Selected) {
using (var bkgrBrush = new SolidBrush(itemColor))
using (var foreBrush = new SolidBrush(e.Item.BackColor)) {
e.Graphics.FillRectangle(bkgrBrush, rect);
e.Graphics.DrawString(e.Item.Text, e.Item.Font, foreBrush, rect, format);
}
e.DrawFocusRectangle();
}
else {
//e.DrawDefault = true;
using (var foreBrush = new SolidBrush(itemColor)) {
e.Graphics.DrawString(e.Item.Text, e.Item.Font, foreBrush, rect, format);
}
}
}
}
// Draws small symbol in the Header beside the normal Text
protected void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
e.DrawBackground();
string extra = (e.ColumnIndex == 1) ? (char)32 + "\u2660" + (char)32 : (char)32 + "\u2663" + (char)32;
using (var brush = new SolidBrush(e.ForeColor)) {
e.Graphics.DrawString(extra + e.Header.Text, e.Font, brush, e.Bounds, StringFormat.GenericTypographic);
}
}
I'm using validation methods for my textboxes in a class named Validators. I'm trying also to draw a rectangle on the textbox which failed to validate.
Im using this code:
private void TextBoxStyle(TextBox textBox)
{
Graphics graphics = textBox.CreateGraphics();
Pen redPen = new Pen(Color.Red);
graphics.DrawRectangle(redPen, textBox.Location.X, textBox.Location.Y, textBox.Width, textBox.Height);
}
/// <summary>
/// Validates TextBoxes for string input.
/// </summary>
public bool ValidateTextBoxes(params TextBox[] textBoxes)
{
foreach (var textBox in textBoxes)
{
if (textBox.Text.Equals(""))
{
Graphics graphics = textBox.CreateGraphics();
Pen redPen = new Pen(Color.Red);
graphics.DrawRectangle(redPen, textBox.Location.X, textBox.Location.Y, textBox.Width, textBox.Height);
return false;
}
}
return true;
}
The problem is... the rectangles wont show. Am I doing something wrong with the code ? If yes, help please.
A couple potential problems I see:
You get the Graphics object for the text box but use the textbox's offset in the form to do the drawing. Net result: the rectangle is translated outside the visible area of the textbox. Try using the location (0,0).
You draw the rectangle as wide as the textbox. Net result: right and bottom edges won't be visible. You should subtract the width of the pen from these values.
While you're at it, check out the ErrorProvider class. It may just take care of your needs off-the-shelf.
write a user control
public partial class UserControl1 : UserControl
{
private string text;
private bool isvalid = true;
public string Text
{
get { return textBox.Text; }
set { textBox.Text = value; }
}
public bool isValid
{
set
{
isvalid = value;
this.Refresh();
}
}
TextBox textBox = new TextBox();
public UserControl1()
{
InitializeComponent();
this.Paint += new PaintEventHandler(UserControl1_Paint);
this.Resize += new EventHandler(UserControl1_Resize);
textBox.Multiline = true;
textBox.BorderStyle = BorderStyle.None;
this.Controls.Add(textBox);
}
private void UserControl1_Resize(object sender, EventArgs e)
{
textBox.Size = new Size(this.Width - 3, this.Height - 2);
textBox.Location = new Point(2, 1);
}
private void UserControl1_Paint(object sender, PaintEventArgs e)
{
if (isvalid)
ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Black, ButtonBorderStyle.Solid);
else
ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
}
}
update:
just added the isvalid property
you can put properties to show the border or not. if the input is valid show normal border and if the control input is invalid show the red border.
Anything drawn directly onto the TextBox will disappear as soon as the TextBox control is invalidated in some way.
A correct approach is to add a User Control to your project and add a TextBox on its canvas. Leave a little border around it.
You can now simply color the background of the user control's canvas red when needed and it will look like a border drawn around the TextBox.
You can add code directly to the user control to validate it whenever the text changes. That way, you only have to write code once and just add as many TextBoxes as you need to your forms or pages.
You shouldn't paint on a control simply from somewhere. The build in painting will override it on the next occasion. The Control has a paint event where you should paint. That will be used whenever painting is needed.
In your validate method you should just store the result of the validation somewhere so that it can be used in the paint event and call Invalidate() so that a repainting is enforced.
// You may use this
Label lblHighlight = new Label ();
Rectangle rc = new Rectangle(this.Left - 2, this.Top - 2, this.Width + 4, this.Bottom - this.Top + 4);
this.Parent.Controls.Add(lblHighlight);
lblHighlight.Bounds = rc;
lblHighlight.BackColor = "Red";
After some search at Google I had some examples but none of them gave me what I need.
I need to write a String (WriteString()) into a Control in WinForm on a ButtonClick and I need to update that Draw, because i'm trying to write the Date into the Control, the System Date.
So each time the user clicks on that Button the DateTime.Now.ToString(); should be drawn into the Control.
Bests
draw a string on label
this url will surely help you
the code written there is
void Label_OnPaint(object sender, PaintEventArgs e) {
base.OnPaint(e);
Label lbl = sender as Label;
if (lbl != null) {
string Text = lbl.Text;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
if (myShowShadow) { // draw the shadow first!
e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(myShadowColor), myShadowOffset, StringFormat.GenericDefault);
}
e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(lbl.ForeColor), 0, 0, StringFormat.GenericDefault);
}
}
You should consider using a winforms Label and a Timer for that.
Or you could modify the OnPaint method of the control to override how the control is painted. There is a method in the Graphics object that lets you write a string g.DrawString
How can I set a form's backcolor to a custom color (such as light pink) using C# code?
If you want to set the form's back color to some arbitrary RGB value, you can do this:
this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish
With Winforms you can use Form.BackColor to do this.
From within the Form's code:
BackColor = Color.LightPink;
If you mean a WPF Window you can use the Background property.
From within the Window's code:
Background = Brushes.LightPink;
Define BackGround Color ShowDialog
ColorDialog bgColor = new ColorDialog();
After if you want change the color according to selected color
bgColor.ShowDialog();
this.BackColor = bgColor.Color;