Windows Forms small MenuItem hitbox - c#

I am using MenuItem.DrawItem to change MenuItem's appearance based on the fact whether user either hovers or select it. Unfortunatelly the hitbox seems too small. Here's my drawing code.
private void DrawCustomMenuItem(object sender,
DrawItemEventArgs e)
{
MenuItem customItem = (MenuItem) sender;
System.Drawing.Brush aBrush = System.Drawing.Brushes.DarkMagenta;
Font aFont = new Font("Arial", 10,
FontStyle.Italic, GraphicsUnit.Point);
SizeF stringSize = e.Graphics.MeasureString(
customItem.Text, aFont);
Pen p = new Pen(Color.Aqua, 2);
if ((e.State & DrawItemState.HotLight) == DrawItemState.HotLight
|| (e.State & DrawItemState.Selected) == DrawItemState.Selected)
p = new Pen(Color.Black, 2);
e.Graphics.DrawString(customItem.Text, aFont,
aBrush, e.Bounds.X, e.Bounds.Y);
e.Graphics.DrawEllipse(p,
new Rectangle(e.Bounds.X, e.Bounds.Y,
(int) stringSize.Width,
(int) stringSize.Height));
}
It only changes color when mouse is nearby left edge of the item. It isn't surprising I guess. I have no code that changes hitbox's dimensions and it is using the default one and I am drawing outside of it. I really have no idea how to approach it. I thought I should use MenuItem.Size to achieve that. But this property doesn't exist.
EDIT:
Ok, I got it. It's all about MeasureItem event. But another problem came up. The MeasureItemEventArgs.Graphics.MeasureString() seems to return too big width for the text. Here are my current functions:
private void Mitem2OnMeasureItem(object sender, MeasureItemEventArgs e)
{
MenuItem item = sender as MenuItem;
if (item == null) return;
var size = e.Graphics.MeasureString(item.Text, f);
e.ItemHeight = (int) size.Height;
e.ItemWidth = (int) size.Width;
}
private void Mitem2OnDrawItem(object sender, DrawItemEventArgs e)
{
MenuItem item = sender as MenuItem;
if (item == null) return;
SizeF size = e.Graphics.MeasureString(item.Text, f);
e.Graphics.FillRectangle(
(e.State & DrawItemState.HotLight) == DrawItemState.HotLight ? Brushes.CornflowerBlue : Brushes.Aqua,
e.Bounds);
e.Graphics.DrawString(item.Text, f, Brushes.Black, e.Bounds.X, e.Bounds.Y);
e.DrawFocusRectangle();
}
This is how it looks like

To get a better measurement use the overload of MeasureString that takes StringFormat class:
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
var size = e.Graphics.MeasureString(
item.Text,
aFont,
new Point(1,1),
StringFormat.GenericTypographic
);
Notice the use of the TextRenderingHint with a value of AntiAlias that is set on the Graphics object.
You'll still have a slightly bigger bounding box but in my test the box is 5 pixels less wide with this code instead of your code.

Related

Winforms ComboBox Height different to ItemHeight

I am using a ComboBox in Text and DropDown mode (the default) and I want to have an ItemHeight of X (e.g. 40) but have the ComboBox's Height set to Y (e.g. 20).
The reason for this is that I am intending to use the ComboBox for a Quick Search feature in which the user keys in text and detailed results are rendered in the list items. Only one line of input is required.
Unfortunately, Winforms automatically locks the ComboBox's Height to the ItemHeight and I can see no way to change this.
How can I make the ComboBox's Height differ to the ItemHeight?
What you have to do is, first of all, change DrawMode from Normal to OwnerDrawVariable. Then you've got to handle 2 events: DrawItem and MeasureItem . They would be something like:
private void comboBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = 40; //Change this to your desired item height
}
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
ComboBox box = sender as ComboBox;
if (Object.ReferenceEquals(null, box))
return;
e.DrawBackground();
if (e.Index >= 0)
{
Graphics g = e.Graphics;
using (Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
? new SolidBrush(SystemColors.Highlight)
: new SolidBrush(e.BackColor))
{
using (Brush textBrush = new SolidBrush(e.ForeColor))
{
g.FillRectangle(brush, e.Bounds);
g.DrawString(box.Items[e.Index].ToString(),
e.Font,
textBrush,
e.Bounds,
StringFormat.GenericDefault);
}
}
}
e.DrawFocusRectangle();
}

C# Winform: How to set the Base Color of a TabControl (not the tabpage) AND use an icon

I applied the solution provided by an user to solve the problem, but it's happening another problem. Previously I owned an icon along with the text, but after I used the code described here, my icon no longer appears. What can it be?
And how can I use the icon while using a different color other than the default on tab header?
The solution I used is:
private void tabControl1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
TabPage CurrentTab = tabControl1.TabPages[e.Index];
Rectangle ItemRect = tabControl1.GetTabRect(e.Index);
SolidBrush FillBrush = new SolidBrush(Color.Red);
SolidBrush TextBrush = new SolidBrush(Color.White);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
//If we are currently painting the Selected TabItem we'll
//change the brush colors and inflate the rectangle.
if (System.Convert.ToBoolean(e.State & DrawItemState.Selected))
{
FillBrush.Color = Color.White;
TextBrush.Color = Color.Red;
ItemRect.Inflate(2, 2);
}
//Set up rotation for left and right aligned tabs
if (tabControl1.Alignment == TabAlignment.Left || tabControl1.Alignment == TabAlignment.Right)
{
float RotateAngle = 90;
if (tabControl1.Alignment == TabAlignment.Left)
RotateAngle = 270;
PointF cp = new PointF(ItemRect.Left + (ItemRect.Width / 2), ItemRect.Top + (ItemRect.Height / 2));
e.Graphics.TranslateTransform(cp.X, cp.Y);
e.Graphics.RotateTransform(RotateAngle);
ItemRect = new Rectangle(-(ItemRect.Height / 2), -(ItemRect.Width / 2), ItemRect.Height, ItemRect.Width);
}
//Next we'll paint the TabItem with our Fill Brush
e.Graphics.FillRectangle(FillBrush, ItemRect);
//Now draw the text.
e.Graphics.DrawString(CurrentTab.Text, e.Font, TextBrush, (RectangleF)ItemRect, sf);
//Reset any Graphics rotation
e.Graphics.ResetTransform();
//Finally, we should Dispose of our brushes.
FillBrush.Dispose();
TextBrush.Dispose();
}
You need to paint the Icon yourself also. An example would be to add something like the following after the painting of the tabs Background in you code (i assume that an image list was used here)
int imageLeftOffset = 4;
Point imagePos = new Point(imageLeftOffset, ItemRect.Top + (ItemRect.Height - tabControl1.ImageList.ImageSize.Height + 1) / 2);
tabControl1.ImageList.Draw(e.Graphics, imagePos, CurrentTab.ImageIndex);
You may need to reajust the drawing of the Text so that text and image aren't overlapping.

Treenode text different colored words

I have a TreeView and each of it's Node.Text has two words.
The first and second words should have different colors. I'm already changing the color of the text with the DrawMode properties and the DrawNode event but I can't figure out how to split the Node.Text in two different colors. Someone pointed out I could use TextRenderer.MeasureText but I have no idead how/where to use it.
Someone has an idea ?
Code :
formload()
{
treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
}
private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
Color nodeColor = Color.Red;
if ((e.State & TreeNodeStates.Selected) != 0)
nodeColor = SystemColors.HighlightText;
TextRenderer.DrawText(e.Graphics,
e.Node.Text,
e.Node.NodeFont,
e.Bounds,
nodeColor,
Color.Empty,
TextFormatFlags.VerticalCenter);
}
Try this:
private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
string[] texts = e.Node.Text.Split();
using (Font font = new Font(this.Font, FontStyle.Regular))
{
using (Brush brush = new SolidBrush(Color.Red))
{
e.Graphics.DrawString(texts[0], font, brush, e.Bounds.Left, e.Bounds.Top);
}
using (Brush brush = new SolidBrush(Color.Blue))
{
SizeF s = e.Graphics.MeasureString(texts[0], font);
e.Graphics.DrawString(texts[1], font, brush, e.Bounds.Left + (int)s.Width, e.Bounds.Top);
}
}
}
You must manage State of node to do appropriated actions.
UPDATE
Sorry, my mistake see updated version. There is no necessary to measure space size because it already contains in texts[0].

Extracting an Event (tabControl_DrawItem) to Class Library

I have the following code under a TabConttrols DrawItem event that I am trying to extract into a class file. I am having trouble since it is tied to an event. Any hints or pointers would be greatly appreciated.
private void tabCaseNotes_DrawItem(object sender, DrawItemEventArgs e)
{
TabPage currentTab = tabCaseNotes.TabPages[e.Index];
Rectangle itemRect = tabCaseNotes.GetTabRect(e.Index);
SolidBrush fillBrush = new SolidBrush(Color.Linen);
SolidBrush textBrush = new SolidBrush(Color.Black);
StringFormat sf = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
//If we are currently painting the Selected TabItem we'll
//change the brush colors and inflate the rectangle.
if (System.Convert.ToBoolean(e.State & DrawItemState.Selected))
{
fillBrush.Color = Color.LightSteelBlue;
textBrush.Color = Color.Black;
itemRect.Inflate(2, 2);
}
//Set up rotation for left and right aligned tabs
if (tabCaseNotes.Alignment == TabAlignment.Left || tabCaseNotes.Alignment == TabAlignment.Right)
{
float rotateAngle = 90;
if (tabCaseNotes.Alignment == TabAlignment.Left)
rotateAngle = 270;
PointF cp = new PointF(itemRect.Left + (itemRect.Width / 2), itemRect.Top + (itemRect.Height / 2));
e.Graphics.TranslateTransform(cp.X, cp.Y);
e.Graphics.RotateTransform(rotateAngle);
itemRect = new Rectangle(-(itemRect.Height / 2), -(itemRect.Width / 2), itemRect.Height, itemRect.Width);
}
//Next we'll paint the TabItem with our Fill Brush
e.Graphics.FillRectangle(fillBrush, itemRect);
//Now draw the text.
e.Graphics.DrawString(currentTab.Text, e.Font, textBrush, (RectangleF)itemRect, sf);
//Reset any Graphics rotation
e.Graphics.ResetTransform();
//Finally, we should Dispose of our brushes.
fillBrush.Dispose();
textBrush.Dispose();
}
Depends on what you're trying to achieve. You could always sub class TabControl or you could encapsulate the drawing code in a class that you pass a TabControl to.
public class TabRenderer
{
private TabControl _tabControl;
public TabRenderer(TabControl tabControl)
{
_tabControl = tabControl;
_tabControl.DrawMode = TabDrawMode.OwnerDrawFixed;
_tabControl.DrawItem += TabControlDrawItem;
}
private void TabControlDrawItem(object sender, DrawItemEventArgs e)
{
// Your drawing code...
}
}

Background color of a ListBox item (Windows Forms)

How can I set the background color of a specific item in a System.Windows.Forms.ListBox?
I would like to be able to set multiple ones if possible.
Thanks for the answer by Grad van Horck. It guided me in the correct direction.
To support text (not just background color), here is my fully working code:
//global brushes with ordinary/selected colors
private SolidBrush reportsForegroundBrushSelected = new SolidBrush(Color.White);
private SolidBrush reportsForegroundBrush = new SolidBrush(Color.Black);
private SolidBrush reportsBackgroundBrushSelected = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
private SolidBrush reportsBackgroundBrush1 = new SolidBrush(Color.White);
private SolidBrush reportsBackgroundBrush2 = new SolidBrush(Color.Gray);
//custom method to draw the items, don't forget to set DrawMode of the ListBox to OwnerDrawFixed
private void lbReports_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);
int index = e.Index;
if (index >= 0 && index < lbReports.Items.Count)
{
string text = lbReports.Items[index].ToString();
Graphics g = e.Graphics;
//background:
SolidBrush backgroundBrush;
if (selected)
backgroundBrush = reportsBackgroundBrushSelected;
else if ((index % 2) == 0)
backgroundBrush = reportsBackgroundBrush1;
else
backgroundBrush = reportsBackgroundBrush2;
g.FillRectangle(backgroundBrush, e.Bounds);
//text:
SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush;
g.DrawString(text, e.Font, foregroundBrush, lbReports.GetItemRectangle(index).Location);
}
e.DrawFocusRectangle();
}
The above adds to the given code and will show the proper text plus highlight the selected item.
Probably the only way to accomplish that is to draw the items yourself.
Set the DrawMode to OwnerDrawFixed and code something like this on the DrawItem event:
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Graphics g = e.Graphics;
g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds);
// Print text
e.DrawFocusRectangle();
}
The second option would be using a ListView, although they have an other way of implementations (not really data bound, but more flexible in way of columns).
// Set the background to a predefined colour
MyListBox.BackColor = Color.Red;
// OR: Set parts of a color.
MyListBox.BackColor.R = 255;
MyListBox.BackColor.G = 0;
MyListBox.BackColor.B = 0;
If what you mean by setting multiple background colors is setting a different background color for each item, this isn't possible with a ListBox, but it is with a ListView, with something like:
// Set the background of the first item in the list
MyListView.Items[0].BackColor = Color.Red;
public MainForm()
{
InitializeComponent();
this.listbox1.DrawItem += new DrawItemEventHandler(this.listbox1_DrawItem);
}
private void listbox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
e.DrawBackground();
Brush myBrush = Brushes.Black;
var item = listbox1.Items[e.Index];
if(e.Index % 2 == 0)
{
e.Graphics.FillRectangle(new SolidBrush(Color.Gold), e.Bounds);
}
e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
e.Font, myBrush,e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
}

Categories

Resources