I am making a height-adjustable and vertically alignable textbox with following code. The reason why I should do this is because although I can make winform textbox height-adjustable, I still can't vertically align the text in the textbox. So I decided I have to draw the text OnPaint event. The textbox is showing correct alignment now, but cursor is still located on top of textbox. Is there any way to control this position as well?
public class TextBoxHeightAdjustable : System.Windows.Forms.TextBox
{
public TextBoxHeightAdjustable()
{
this.AutoSize = false;
this.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
}
protected override void OnPaint(PaintEventArgs e)
{
// This never runs no matter what I try!
base.OnPaint(e);
// Create a StringFormat object with the each line of text, and the block
// of text centered on the page.
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle, stringFormat);
}
}
In spite of Hans' advice, I proceeded since the textbox will contain simple numeric-like text. As Hans said, there is not much option for us to deal with original cursor and lively displayed text. So I hided them with following extension method and by disabling double-clicking and keypress update.
[DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);
public static void HideCaret(this TextBox textBox)
{
HideCaret(textBox.Handle);
}
So eventually following code works for my purpose but I can't say it's complete. I may still figure out how to draw my own cursor. Hope this helps others with similar issue.
public class TextBoxHeightAdjustable : System.Windows.Forms.TextBox
{
const int WM_DBLCLICK = 0xA3;
const int WM_LBUTTONDBLCLK = 0x203;
public TextBoxHeightAdjustable() : base()
{
this.AutoSize = false;
this.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
//base.OnKeyPress(e);
if (e.KeyChar == (char)Keys.Back)
{
Text = Text.Remove(Text.Length-1);
}
else
{
Text += e.KeyChar;
}
e.Handled = true;
}
protected override void WndProc(ref Message m)
{
if ((m.Msg == WM_DBLCLICK) || (m.Msg == WM_LBUTTONDBLCLK))
{
}
else
{
base.WndProc(ref m);
}
}
protected override void OnTextChanged(System.EventArgs args)
{
//KeyEventArgs kpe = (KeyEventArgs) args;
//this.Font = new Font(this.Font.FontFamily, 0);
using (Graphics g = this.CreateGraphics())
{
g.FillRectangle(Brushes.White, ClientRectangle);
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
g.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle, stringFormat);
}
}
protected override void OnPaint(PaintEventArgs e)
{
this.HideCaret();
e.Graphics.FillRectangle(Brushes.White, ClientRectangle);
// This never runs no matter what I try!
//base.OnPaint(e);
// Create a StringFormat object with the each line of text, and the block
// of text centered on the page.
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle, stringFormat);
}
}
Related
I've extended WinForms TreeView in C# in order to draw my own text (I'm drawing a shadowed font with black under white) and everything looks okay apart from when I expand a node with a large number of children (by large I'm only talking 20+). I've tried to capture what happens but it's so quick I've been unsuccessful so I'll try to explain it.
The TreeView has around 15 1st level nodes in it and when I open one of the 20+ children nodes, I get a glitch where it displays the node under the one I've clicked multiple times (looks like the same amount of times as the children nodes that subsequently appear) for an instant and then displays all the child nodes. It's very frustrating, mostly because I can't find anything online similar to this.
I've set the TreeView to use double buffering but although it covers lots of flicking, it doesn't cover this glitch.
Here's my TreeView class:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Liq.CommonControls.Tree
{
public partial class LiqTreeView : TreeView
{
private Brush backBrush, highlightBrush, blackBrush, textBrush;
private Font drawFont;
private const int TVM_SETEXTENDEDSTYLE = 0x1100 + 44;
private const int TVM_GETEXTENDEDSTYLE = 0x1100 + 45;
private const int TVS_EX_DOUBLEBUFFER = 0x0004;
private const int WM_ERASEBKGND = 0x0014;
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
public LiqTreeView()
{
InitializeComponent();
this.DrawNode += LiqTreeView_DrawNode;
BackColor = Color.FromArgb(255, 105, 105, 105);
backBrush = new SolidBrush(this.BackColor);
highlightBrush = new SolidBrush(Color.LightGray);
blackBrush = new SolidBrush(Color.Black);
textBrush = new SolidBrush(Color.WhiteSmoke);
drawFont = new Font("Arial", 14, FontStyle.Bold, GraphicsUnit.Pixel);
}
protected override void OnHandleCreated(EventArgs e)
{
SendMessage(this.Handle, TVM_SETEXTENDEDSTYLE, (IntPtr)TVS_EX_DOUBLEBUFFER, (IntPtr)TVS_EX_DOUBLEBUFFER);
base.OnHandleCreated(e);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_ERASEBKGND)
{
m.Result = IntPtr.Zero;
return;
}
base.WndProc(ref m);
}
private void LiqTreeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
if (e.Bounds.Height < 1 || e.Bounds.Width < 1) return;
e.DrawDefault = false;
if (!e.Node.IsVisible)
return;
if (e.Node.IsSelected)
e.Graphics.FillRectangle(highlightBrush, e.Bounds);
Rectangle r = e.Bounds;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Near;
sf.LineAlignment = StringAlignment.Near;
sf.Trimming = StringTrimming.Character;
r.Y -= 2;
r.X += e.Node.Level * 10;
TextRenderer.DrawText(e.Graphics, e.Node.Text, drawFont, (Rectangle)r, Color.Black, TextFormatFlags.Left|TextFormatFlags.EndEllipsis);
r.Y -= 1;
r.X += 1;
TextRenderer.DrawText(e.Graphics, e.Node.Text, drawFont, (Rectangle)r, Color.WhiteSmoke, TextFormatFlags.Left | TextFormatFlags.EndEllipsis);
}
}
}
I have been having an issue when using the OnPaint event on a TextBox.
Whenever I click on the text area with the mouse or when I start to type, the background of the text box changes back to white. Any idea what can cause that?
Here is my code:
protected override void OnCreateControl() {
base.OnCreateControl();
SetStyle(ControlStyles.OptimizedDoubleBuffer
| ControlStyles.DoubleBuffer
| ControlStyles.AllPaintingInWmPaint
| ControlStyles.ResizeRedraw
| ControlStyles.UserPaint, true);
}
protected override void OnPaintBackground(PaintEventArgs e) {
SolidBrush bBrush = new SolidBrush(Enabled ? BackColor : Color.LightGray);
e.Graphics.FillRectangle(bBrush, ClientRectangle);
bBrush.Dispose();
}
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
using (Brush aBrush = new SolidBrush(ForeColor)) {
StringFormat sf = new StringFormat();
switch (TextAlign) {
case HorizontalAlignment.Center:
sf.Alignment = StringAlignment.Center;
break;
case HorizontalAlignment.Left:
sf.Alignment = StringAlignment.Near;
break;
case HorizontalAlignment.Right:
sf.Alignment = StringAlignment.Far;
break;
}
string text = UseSystemPasswordChar && !Enabled
? new StringBuilder(Text.Length).Insert(0, PasswordChar.ToString(), Text.Length).ToString()
: Text;
e.Graphics.DrawString(text, (Font)Font.Clone(), aBrush, ClientRectangle, sf);
aBrush.Dispose();
}
}
I made custom combobox that have an integrated button to add new item and it works good in case when DropDownStyle = ComboBoxStyle.DropDownList but there is a problem when the combobox DropDownStyle = ComboBoxStyle.DropDown the text of the combobox is cover the button that I made.
Is there away to make space before text in case when the DropDownStyle for the combobox is set to DropDown? You can see the problem in image.
[Image showing the spacing issue on the combobox]1
public class ComboBoxButton3 : ComboBox
{
public ComboBoxButton3()
{
myButton = new Button();
this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.DropDownStyle = ComboBoxStyle.DropDownList;
}
protected override void OnCreateControl()
{
this.myButton.Size = new Size(23, this.ClientSize.Height);
this.myButton.Location = new Point(0, 0);
this.myButton.Cursor = Cursors.Default;
this.Button.BackgroundImage = global::RibbonMenuControlTest.Properties.Resources.add1;
this.Button.BackgroundImageLayout = ImageLayout.Stretch;
this.Button.FlatStyle = FlatStyle.Flat;
this.Controls.Add(this.myButton);
base.OnCreateControl();
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (this != null)
{
e.DrawBackground();
if (e.Index >= 0)
{
StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
Brush brush = new SolidBrush(this.ForeColor);
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
brush = SystemBrushes.HighlightText;
e.Graphics.DrawString(this.Items[e.Index].ToString(), this.Font, brush, e.Bounds, sf);
}
}
base.OnDrawItem(e);
}
public Button myButton;
public Button Button
{
get
{
return myButton;
}
set
{
myButton = value;
}
}
}
Generally, if a control is not designed to do a certain function with ease, there is normally a reason for it.
I would suggest re-considering your design before going forward.
Regardless, if you insist and continue - then these threads should give you the desired result / point you in the right direction (at least with moving the text around).
Align Text in Combobox
http://blog.michaelgillson.org/2010/05/18/left-right-center-where-do-you-align/
Snippet:
I have a custom TextBox in which I draw some place holder text when it's empty.
It works pretty well, but it flickers when the mouse enters and leaves the TextBox. It seems related to the border becoming blue when the mouse hovers the control (I'm on Windows 8.1).
Any idea how I could fix this ?
I've tried various SetStyles flags without success.
class MyTextBox : TextBox
{
public string PlaceHolder { get; set; }
static readonly Brush sPlaceHolderBrush = new SolidBrush(Color.FromArgb(70, 70, 78));
static readonly StringFormat sFormat = new StringFormat
{
Alignment = StringAlignment.Near,
LineAlignment = StringAlignment.Center
};
private Font mPlaceHolderFont;
[DllImport("user32")]
private static extern IntPtr GetWindowDC(IntPtr hwnd);
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x0F)
{
if (string.IsNullOrEmpty(Text) && !Focused)
{
IntPtr dc = GetWindowDC(Handle);
using (Graphics g = Graphics.FromHdc(dc))
{
if (mPlaceHolderFont == null)
mPlaceHolderFont = new Font(Font, FontStyle.Italic);
var rect = new RectangleF(2, 2, Width - 4, Height - 4);
g.FillRectangle(Brushes.White, rect);
g.DrawString(PlaceHolder, mPlaceHolderFont, sPlaceHolderBrush, rect, sFormat);
}
}
}
}
}
I had other problems with overriding OnPaint. Here is the best solution I came up with :
class MyTextBox : TextBox
{
public string PlaceHolder { get; set; }
static readonly Brush sPlaceHolderBrush = new SolidBrush(Color.FromArgb(70, 70, 78));
static readonly StringFormat sFormat = new StringFormat
{
Alignment = StringAlignment.Near,
LineAlignment = StringAlignment.Near
};
private Font mPlaceHolderFont;
private Brush mForegroundBrush;
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
var bounds = new Rectangle(-2, -2, Width, Height);
var rect = new RectangleF(1, 0, Width - 2, Height - 2);
e.Graphics.FillRectangle(Brushes.White, rect);
if (string.IsNullOrEmpty(Text) && !Focused)
{
if (mPlaceHolderFont == null)
mPlaceHolderFont = new Font(Font, FontStyle.Italic);
if (mForegroundBrush == null)
mForegroundBrush = new SolidBrush(ForeColor);
e.Graphics.DrawString(PlaceHolder, mPlaceHolderFont, sPlaceHolderBrush, rect, sFormat);
}
else
{
var flags = TextFormatFlags.Default | TextFormatFlags.TextBoxControl;
if (!Multiline)
flags |= TextFormatFlags.SingleLine | TextFormatFlags.NoPadding;
TextBoxRenderer.DrawTextBox(e.Graphics, bounds, Text, Font, flags, TextBoxState.Selected);
}
}
}
Is there a special reason for using WM_PAINT instead of OnPaint? In WM_PAINT you obtain a drawing context from the handle, which is always a direct access to the control. In OnPaint you already have a Graphics in the event args, which can be either a buffer or a direct context, depending on the styles.
You mentioned that you have tried a few styles with no success. Firstly I would say try these and move your paint logic into OnPaint:
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
If it does not work (a focused control may behave strangely in Windows) and you must stick to WM_PAINT, then create a buffer manually. Your original code draws a white rectangle first, then some text, which causes flickering. You can avoid this by using a buffer:
IntPtr dc = GetWindowDC(Handle);
using (Graphics g = Graphics.FromHdc(dc))
{
// creating a buffered context
using (BufferedGraphicsContext context = new BufferedGraphicsContext())
{
// creating a buffer for the original Graphics
using (BufferedGraphics bg = context.Allocate(e.Graphics, ClientRectangle))
{
if (mPlaceHolderFont == null)
mPlaceHolderFont = new Font(Font, FontStyle.Italic);
var gBuf = bg.Graphics;
var rect = ClientRectangle;
rect.Inflate(-1, -1);
gBuf.FillRectangle(Brushes.White, rect);
gBuf.DrawString(PlaceHolder, mPlaceHolderFont, sPlaceHolderBrush, rect, sFormat);
// copying the buffer onto the original Graphics
bg.Render(e.Graphics);
}
}
}
How can I change the BorderColor of the Textbox when a user Clicks on it or focuses on it?
You can handle WM_NCPAINT message of TextBox and draw a border on the non-client area of control if the control has focus. You can use any color to draw border:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ExTextBox : TextBox
{
[DllImport("user32")]
private static extern IntPtr GetWindowDC(IntPtr hwnd);
private const int WM_NCPAINT = 0x85;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCPAINT && this.Focused)
{
var dc = GetWindowDC(Handle);
using (Graphics g = Graphics.FromHdc(dc))
{
g.DrawRectangle(Pens.Red, 0, 0, Width - 1, Height - 1);
}
}
}
}
Result
The painting of borders while the control is focused is completely flicker-free:
BorderColor property for TextBox
In the current post I just change the border color on focus. You can also add a BorderColor property to the control. Then you can change border-color based on your requirement at design-time or run-time. I've posted a more completed version of TextBox which has BorderColor property:
in the following post:
BorderColor property for TextBox
try this
bool focus = false;
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (focus)
{
textBox1.BorderStyle = BorderStyle.None;
Pen p = new Pen(Color.Red);
Graphics g = e.Graphics;
int variance = 3;
g.DrawRectangle(p, new Rectangle(textBox1.Location.X - variance, textBox1.Location.Y - variance, textBox1.Width + variance, textBox1.Height +variance ));
}
else
{
textBox1.BorderStyle = BorderStyle.FixedSingle;
}
}
private void textBox1_Enter(object sender, EventArgs e)
{
focus = true;
this.Refresh();
}
private void textBox1_Leave(object sender, EventArgs e)
{
focus = false;
this.Refresh();
}
This is an ultimate solution to set the border color of a TextBox:
public class BorderedTextBox : UserControl
{
TextBox textBox;
public BorderedTextBox()
{
textBox = new TextBox()
{
BorderStyle = BorderStyle.FixedSingle,
Location = new Point(-1, -1),
Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
AnchorStyles.Left | AnchorStyles.Right
};
Control container = new ContainerControl()
{
Dock = DockStyle.Fill,
Padding = new Padding(-1)
};
container.Controls.Add(textBox);
this.Controls.Add(container);
DefaultBorderColor = SystemColors.ControlDark;
FocusedBorderColor = Color.Red;
BackColor = DefaultBorderColor;
Padding = new Padding(1);
Size = textBox.Size;
}
public Color DefaultBorderColor { get; set; }
public Color FocusedBorderColor { get; set; }
public override string Text
{
get { return textBox.Text; }
set { textBox.Text = value; }
}
protected override void OnEnter(EventArgs e)
{
BackColor = FocusedBorderColor;
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e)
{
BackColor = DefaultBorderColor;
base.OnLeave(e);
}
protected override void SetBoundsCore(int x, int y,
int width, int height, BoundsSpecified specified)
{
base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
}
}
WinForms was never good at this and it's a bit of a pain.
One way you can try is by embedding a TextBox in a Panel and then manage the drawing based on focus from there:
public class BorderTextBox : Panel {
private Color _NormalBorderColor = Color.Gray;
private Color _FocusBorderColor = Color.Blue;
public TextBox EditBox;
public BorderTextBox() {
this.DoubleBuffered = true;
this.Padding = new Padding(2);
EditBox = new TextBox();
EditBox.AutoSize = false;
EditBox.BorderStyle = BorderStyle.None;
EditBox.Dock = DockStyle.Fill;
EditBox.Enter += new EventHandler(EditBox_Refresh);
EditBox.Leave += new EventHandler(EditBox_Refresh);
EditBox.Resize += new EventHandler(EditBox_Refresh);
this.Controls.Add(EditBox);
}
private void EditBox_Refresh(object sender, EventArgs e) {
this.Invalidate();
}
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.Clear(SystemColors.Window);
using (Pen borderPen = new Pen(this.EditBox.Focused ? _FocusBorderColor : _NormalBorderColor)) {
e.Graphics.DrawRectangle(borderPen, new Rectangle(0, 0, this.ClientSize.Width - 1, this.ClientSize.Height - 1));
}
base.OnPaint(e);
}
}
Using OnPaint to draw a custom border on your controls is fine. But know how to use OnPaint to keep efficiency up, and render time to a minimum. Read this if you are experiencing a laggy GUI while using custom paint routines: What is the right way to use OnPaint in .Net applications?
Because the accepted answer of PraVn may seem simple, but is actually inefficient. Using a custom control, like the ones posted in the answers above is way better.
Maybe the performance is not an issue in your application, because it is small, but for larger applications with a lot of custom OnPaint routines it is a wrong approach to use the way PraVn showed.
set Text box Border style to None
then write this code to container form "paint" event
private void Form1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Rectangle rect = new Rectangle(TextBox1.Location.X,
TextBox1.Location.Y, TextBox1.ClientSize.Width, TextBox1.ClientSize.Height);
rect.Inflate(1, 1); // border thickness
System.Windows.Forms.ControlPaint.DrawBorder(e.Graphics, rect,
Color.DeepSkyBlue, ButtonBorderStyle.Solid);
}
With PictureBox1
.Visible = False
.Width = TextBox1.Width + 4
.Height = TextBox1.Height + 4
.Left = TextBox1.Left - 2
.Top = TextBox1.Top - 2
.SendToBack()
.Visible = True
End With
Here is my complete Flat TextBox control that supports themes including custom border colors in normal and focused states.
The control uses the same concept mentioned by Reza Aghaei https://stackoverflow.com/a/38405319/5514131 ,however the FlatTextBox control is more customizable and flicker-free.
The control handles the WM_NCPAINT window message in a better way to help eliminate flicker.
Protected Overrides Sub WndProc(ByRef m As Message)
If m.Msg = WindowMessage.WM_NCPAINT AndAlso _drawBorder AndAlso Not DesignMode Then 'Draw the control border
Dim w As Integer
Dim h As Integer
Dim clip As Rectangle
Dim hdc As IntPtr
Dim clientRect As RECT = Nothing
GetClientRect(Handle, clientRect)
Dim windowRect As RECT = Nothing
GetWindowRect(Handle, windowRect)
w = windowRect.Right - windowRect.Left
h = windowRect.Bottom - windowRect.Top
clip = New Rectangle(CInt((w - clientRect.Right) / 2), CInt((h - clientRect.Bottom) / 2), clientRect.Right, clientRect.Bottom)
hdc = GetWindowDC(Handle)
Using g As Graphics = Graphics.FromHdc(hdc)
g.SetClip(clip, CombineMode.Exclude)
Using sb = New SolidBrush(BackColor)
g.FillRectangle(sb, 0, 0, w, h)
End Using
Using p = New Pen(If(Focused, _borderActiveColor, _borderNormalColor), BORDER_WIDTH)
g.DrawRectangle(p, 0, 0, w - 1, h - 1)
End Using
End Using
ReleaseDC(Handle, hdc)
Return
End If
MyBase.WndProc(m)
End Sub
I have removed the default BorderStyle property and replaced it with a simple boolean DrawBorder property that controls whether to draw a border around the control or not.
Use the BorderNormalColor property to specify the border color when the TextBox has no focus, and the BorderActiveColor property to specify the border color when the control receives focus.
The FlatTextBox comes with two themes VS2019 Dark and VS2019 Light, use the Theme property to switch between them.
Complete FlatTextBox control code written in VB.NET
https://gist.github.com/ahmedosama007/37fe2004183a51a4ea0b4a6dcb554176