Custom Color Dialog in Windows Forms - c#

Is there a way to have the color dialog display on the form without the window border? To make things a bit more clearer, I want it sort of like the one used in the Paint program so that I'm able to change colors of lines drawn on a picturebox without having to open up the dialog again and again:
I'm placing it inside a vertical groupbox, and I want it to be able to fit in it. Can it be done?

You can easily build it yourself. Use a TableLayoutPanel or FlowLayoutPanel and a add a list of small PictureBox with the background color set on the color you want. Then handle the Click event to return/use their background color.
private void Form1_Load(object sender, EventArgs e)
{
pictureBox3.Click += HandleColorPick;
pictureBox4.Click += HandleColorPick;
pictureBox5.Click += HandleColorPick;
pictureBox6.Click += HandleColorPick;
pictureBox7.Click += HandleColorPick;
pictureBox8.Click += HandleColorPick;
pictureBox9.Click += HandleColorPick;
}
private void HandleColorPick(object sender, EventArgs e)
{
var s =(PictureBox) sender;
MessageBox.Show(s.BackColor.ToString());
}

You'll have to create your own palette.
Here's a usercontrol i wrote with comments. I've added a OnSelectionChanged event that will be fired when user changes color.
You can either use the designer to specify colors, events and other properties or you can hard-code them.
public partial class UserControl1 : UserControl
{
// The event raised when a user changes color
[Category("Behavior")]
public event EventHandler OnSelectionChanged;
/*
* Properties
*
*/
private Color[] m_Colors = new Color[] {}; // Colors on the palette
private Color m_SelectedColor; // Stores selected color
private int m_MaxColorsPerLine = 14; // Max colors per line
public Color[] Colors
{
get { return m_Colors; }
set { m_Colors = value; }
}
[Browsable(false)]
public Color SelectedColor
{
get { return m_SelectedColor; }
}
public int MaxColorsPerLine
{
get { return m_MaxColorsPerLine; }
set { m_MaxColorsPerLine = value; }
}
public UserControl1()
{
InitializeComponent();
}
private void UserControl1_Load(object sender, EventArgs e)
{
this.Controls.Clear();
int COLOR_WIDTH = 16;
int COLOR_HEIGHT = 16;
// Border colors
Color NEUTRAL_COLOR = Color.Black;
Color HIGHLIGHTED_COLOR = Color.Orange;
Color SELECTED_COLOR = Color.Red;
// Populate the palette
for(int i = 0; i < m_Colors.Length; ++i)
{
// Get where the current color should be positioned.
int linePos = (int)Math.Floor((double) i / m_MaxColorsPerLine);
int colPos = i % m_MaxColorsPerLine;
int posX = COLOR_WIDTH * colPos;
int posY = COLOR_HEIGHT * linePos;
// Create the panel that will hold the color
Panel pnl = new Panel();
pnl.Width = COLOR_WIDTH;
pnl.Height = COLOR_HEIGHT;
pnl.Location = new Point(posX, posY);
pnl.BackColor = m_Colors[i];
pnl.ForeColor = NEUTRAL_COLOR;
// Change border color when highlighted
pnl.MouseEnter += (s, args) => pnl.ForeColor = HIGHLIGHTED_COLOR;
// Change border color when mouse leaves
pnl.MouseLeave += (s, args) =>
{
if (pnl.Tag != null && (bool)pnl.Tag == true)
{
pnl.ForeColor = SELECTED_COLOR; // restore selected border color on mouse leave if selected
}
else
{
pnl.ForeColor = NEUTRAL_COLOR; // restore normal border color on mouse leave if not selected
}
};
// Change border color when selected
pnl.Click += (s, args) =>
{
if (pnl.Tag == null || (bool)pnl.Tag == false)
{
pnl.ForeColor = SELECTED_COLOR;
pnl.Tag = true; // Use the Tag member to store whether the color is selected
m_SelectedColor = pnl.BackColor;
// Raise the SelectionChanged event if this panel is not already selected
if (OnSelectionChanged != null)
{
OnSelectionChanged(this, EventArgs.Empty);
}
}
// Unselect other colors
foreach (Panel otherColor in this.Controls)
{
if (otherColor == pnl)
continue;
if (pnl.Tag != null && (bool)pnl.Tag == true)
{
otherColor.ForeColor = NEUTRAL_COLOR;
otherColor.Tag = false;
}
}
};
// Draw borders
pnl.Paint += (s, args) =>
{
Rectangle outterRect = args.ClipRectangle;
Rectangle innerRect = new Rectangle(outterRect.X + 1, outterRect.Y + 1, outterRect.Width - 3, outterRect.Height - 3);
// Draw outter rectangle
args.Graphics.DrawRectangle(
new Pen(
new SolidBrush(pnl.ForeColor), 2),
outterRect);
// Draw inner rectangle
args.Graphics.DrawRectangle(
new Pen(
Brushes.White, 1),
innerRect);
};
// Finally, add color panel to the control
this.Controls.Add(pnl);
}
}
}

Why not some 3rd party opensource control?
http://www.codeproject.com/Tips/638824/Yet-Another-Color-Picker-for-Csharp-VB-NET-WinForm
or
http://www.blackbeltcoder.com/Articles/controls/colorpicker-controls-for-winforms

Related

C# - show child control (Listbox) on top of parent control(textbox) in winform

Created a custom intellisense textbox (textbox with listbox a child).
As shown in below image, the listbox pops up when i enter a char which all works fine and good but when i am at the end of textbox the listbox is partially visible, is there anyway i can show the whole listbox content?
Tried this "Show control inside user control outside the boundaries of its parent
But when the popup window opens the text box looses focus and i cannot type anything further, my intellisense textbox keeps giving better results based on what they type but in this situation i am not able to type anymore.
FYI tried to add pParentControl.Focus() into show method defined in other article as shown below, missing something?
public void Show(Control pParentControl)
{
if (pParentControl == null) return;
// position the popup window
var loc = pParentControl.PointToScreen(new Point(0, pParentControl.Height));
pParentControl.Focus();
m_tsdd.Show(loc);
}
Here is the complete code
class TextBox_AutoComplete : TextBox
{
#region Class Members
List<string> dictionary;
ListBox listbox = new ListBox();
#endregion
private PopupHelper m_popup;
#region Extern functions
[DllImport("user32")]
private extern static int GetCaretPos(out Point p);
#endregion
#region Constructors
public TextBox_AutoComplete() : base()
{
this.Margin = new Padding(0, 0, 0, 0);
this.Multiline = true;
this.Dock = DockStyle.Fill;
this.KeyDown += Textbox_KeyDown;
this.KeyUp += Textbox_KeyUp;
listbox.Parent = this;
listbox.KeyUp += List_OnKeyUp;
listbox.Visible = false;
this.dictionary = new List<string>();
}
#endregion
#region Properties
public List<string> Dictionary
{
get { return this.dictionary; }
set { this.dictionary = value; }
}
#endregion
#region Methods
private static string GetLastString(string s)
{
Regex rgx = new Regex("[^a-zA-Z0-9_.\\[\\]]");
s = rgx.Replace(s, " ");
string[] strArray = s.Split(' ');
return strArray[strArray.Length - 1];
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
Point cp;
GetCaretPos(out cp);
List<string> lstTemp = new List<string>();
List<string> TempFilteredList = new List<string>();
string LastString = GetLastString(this.Text.Substring(0, SelectionStart));
//MessageBox.Show(LastString);
/*seperated them so that column name matches are found first*/
TempFilteredList.AddRange(dictionary.Where(n => n.Replace("[", "").ToUpper().Substring(n.IndexOf(".") > 0 ? n.IndexOf(".") : 0).StartsWith(LastString.ToUpper())
).Select(r => r)
.ToList());
TempFilteredList.AddRange(dictionary.Where(n => n.Replace("[", "").ToUpper().StartsWith(LastString.ToUpper())
|| n.ToUpper().StartsWith(LastString.ToUpper()))
.Select(r => r)
.ToList());
lstTemp = TempFilteredList.Distinct().Select(r => r).ToList();
/*Getting max width*/
int maxWidth = 0, temp = 0;
foreach (var obj in lstTemp)
{
temp = TextRenderer.MeasureText(obj.ToString(), new Font("Arial", 10, FontStyle.Regular)).Width;
if (temp > maxWidth)
{
maxWidth = temp;
}
}
listbox.SetBounds(cp.X + 20, cp.Y + 20, maxWidth, 60);
if (lstTemp.Count != 0 && LastString != "")
{
listbox.DataSource = lstTemp;
// listbox.Show();
if (m_popup == null)
m_popup = new PopupHelper(listbox);
m_popup.Show(this);
}
else if (m_popup != null)
{
//listbox.Hide();
m_popup.Hide();
}
}
protected void Textbox_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
if (listbox.Visible == true)
{
listbox.Focus();
}
e.Handled = true;
}
else if (e.KeyCode == Keys.Escape)
{
listbox.Visible = false;
e.Handled = true;
}
}
protected void Textbox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space && listbox.Visible == true)
{
listbox.Focus();
List_OnKeyUp(listbox, new KeyEventArgs(Keys.Space));
e.Handled = true;
}
if (e.KeyCode == Keys.Down && listbox.Visible == true)
{
listbox.Focus();
e.Handled = true;
}
}
private void List_OnKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space || e.KeyCode == Keys.Enter)
{
int Selection_Start = this.SelectionStart;
string StrLS = GetLastString(this.Text.Substring(0, Selection_Start));
this.Select(Selection_Start - StrLS.Length, StrLS.Length);
// MessageBox.Show(this.Selection_Start.ToString() + " Last string" + StrLS);
this.SelectedText=((ListBox)sender).SelectedItem.ToString();
listbox.Hide();
this.Focus();
}
}
#endregion
}
public sealed class PopupHelper : IDisposable
{
private readonly Control m_control;
private readonly ToolStripDropDown m_tsdd;
private readonly Panel m_hostPanel; // workarround - some controls don't display correctly if they are hosted directly in ToolStripControlHost
public PopupHelper(Control pControl)
{
m_hostPanel = new Panel();
m_hostPanel.Padding = Padding.Empty;
m_hostPanel.Margin = Padding.Empty;
m_hostPanel.TabStop = false;
m_hostPanel.BorderStyle = BorderStyle.None;
m_hostPanel.BackColor = Color.Transparent;
m_tsdd = new ToolStripDropDown();
m_tsdd.CausesValidation = false;
m_tsdd.Padding = Padding.Empty;
m_tsdd.Margin = Padding.Empty;
m_tsdd.Opacity = 0.9;
m_control = pControl;
m_control.CausesValidation = false;
m_control.Resize += MControlResize;
//m_hostPanel.Controls.Add(m_control);
m_tsdd.Padding = Padding.Empty;
m_tsdd.Margin = Padding.Empty;
m_tsdd.MinimumSize = m_tsdd.MaximumSize = m_tsdd.Size = pControl.Size;
m_tsdd.Items.Add(new ToolStripControlHost(m_control));
}
private void ResizeWindow()
{
m_tsdd.MinimumSize = m_tsdd.MaximumSize = m_tsdd.Size = m_control.Size;
m_hostPanel.MinimumSize = m_hostPanel.MaximumSize = m_hostPanel.Size = m_control.Size;
}
private void MControlResize(object sender, EventArgs e)
{
ResizeWindow();
}
/// <summary>
/// Display the popup and keep the focus
/// </summary>
/// <param name="pParentControl"></param>
public void Show(Control pParentControl)
{
if (pParentControl == null) return;
// position the popup window
var loc = pParentControl.PointToScreen(new Point(0, pParentControl.Height));
pParentControl.Focus();
m_tsdd.Show(loc);
}
public void Hide()
{
m_tsdd.Hide();
}
public void Close()
{
m_tsdd.Close();
}
public void Dispose()
{
m_control.Resize -= MControlResize;
m_tsdd.Dispose();
m_hostPanel.Dispose();
}
}
Firstly, I personally don't see any benefit in having a control inside another. Yes, the child control is locked inside its parent's boundaries automatically for you, but this benefit is negated by the issue that you're facing, and solving that issue requires the same work as when the two controls have no relation. In both cases, you'll have to do the calculations manually to keep the child visible inside its parent. In the second case the parent is the app's window.
Secondly, I don't recommend using hacks like the one mentioned in the comments to show the child outside its parent's boundaries. The hack creates more issues than it solves, as you found out. And what's the point of that hack anyway? If you want to show the child outside the parent, then don't make it a child control in the first place, and you don't need any hack.
The best solution is the one that you find in any well designed app, and in Windows itself. Open any app, let's say Notepad, and right-click near the upper-left corner. You'll see the context menu pulling to lower-right direction. Now right-click near the other three corners and you'll see the context menu pulling in different direction each time, so it will always be visible inside the app. Now if you resize the app window too small and right-click, the context menu will choose the best direction but some of it will be outside the app because the window is too small. That's why you need your list not to be a child, but it's up to you, and it's only about these edge cases. The solution will be similar in both cases.
You're displaying the list in this line:
listbox.SetBounds(cp.X + 20, cp.Y + 20, maxWidth, 60);
The key is cp.X and cp.Y. This is what decides where the list will appear. You need to make this point dynamic and responsive to the boundaries of the parent. You fixed the width to maxWidth and height to 60, so I will use those values in the calculation.
To make sure the list will not go beyond the bottom:
var y = this.Height < cp.Y + 60 ? this.Height - 60 : cp.Y;
To make sure the list will not go beyond the right:
var x = this.Width < cp.X + maxWidth ? this.Width - maxWidth : cp.X;
Now you can show your list at the calculated point:
listbox.SetBounds(x, y, maxWidth, 60);
Notes:
I didn't include the 20 gap that you used. I think it looks better without the gap and I haven't seen any app that has a gap. If you prefer the gap, add it to the calculation of x and y. Don't add it in the SetBounds() or that will screw up the calculation.
The calculation above doesn't take into account when the parent size is too small to show the child inside. If you want to support that edge case, you need to make the child a separate control and add some checks to the calculation.

Adding Custom Controls to a panel programatically with margin

Hello I made a custom text box with an associated label.
and I have a custom Form.
when on a form if I drag drop my custom textbox from the toolbox and set it's properties I can see that it works. However what I would like to do is when I'm on my custom control where I have a TableLayoutPanel (with 3 rows)
on row index 1(mid row) I would like to add my custom controls programatically.
when I do this the text label is somewhere else then the textbox.
My Code and the Image to my problem is below:
MyCustomTextBox:
public class MyLbTextBox : TextBox
{
#region CustomProperties
private Label AssociatedLabel = new Label();
private string _myLbText;
public string MyTextLabel
{
get => _myLbText;
set
{
_myLbText = value;
AssociatedLabel.Text = _myLbText ?? _myBindingField;
Size s = TextRenderer.MeasureText(AssociatedLabel.Text, AssociatedLabel.Font);
AssociatedLabel.Location =
new Point(Location.X - s.Width - AssociatedLabel.Padding.Right, Location.Y);
var MyMargin = this.Margin;
MyMargin.Left = 100;
this.Margin = MyMargin;
}
}
#endregion
private string _myBindingField;
public string MyBindingField
{
get { return _myBindingField; }
set
{
_myBindingField = value;
}
}
private MyJoins.MyExpressions _myExpression;
public MyJoins.MyExpressions MyExpression
{
get => _myExpression;
set => _myExpression = value;
}
public MyLbTextBox()
{
_myExpression = MyJoins.MyExpressions.Equals;
ParentChanged += MyLbTextBox_ParentChanged;
LocationChanged += MyLbTextBox_LocationChanged;
Disposed += MyLbTextBox_Disposed;
}
private void MyLbTextBox_Disposed(object sender, EventArgs e)
{
AssociatedLabel.Dispose();
}
private void MyLbTextBox_LocationChanged(object sender, EventArgs e)
{
Size s = TextRenderer.MeasureText(AssociatedLabel.Text, AssociatedLabel.Font);
AssociatedLabel.Location =
new Point(Location.X - s.Width - AssociatedLabel.Padding.Right, Location.Y);
}
private void MyLbTextBox_ParentChanged(object sender, EventArgs e)
{
AutoAddAssociatedLabel();
}
private void AutoAddAssociatedLabel()
{
if (Parent == null) return;
AssociatedLabel.Padding = new Padding(3);
Size s = TextRenderer.MeasureText(AssociatedLabel.Text, AssociatedLabel.Font);
AssociatedLabel.Location =
new Point(Location.X - s.Width - AssociatedLabel.Padding.Right, Location.Y);
Parent.Controls.Add(AssociatedLabel);
}
}
By the way, this is how I add my controls:
after adding my controls through the property grid
this is how I set them on the screen
private void _mySearchFields_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (_mySearchFields == null) return;
foreach (var searchField in _mySearchFields)
{
if (MySearchFieldsPanel.Contains(searchField.MyControl)) continue;
MySearchFieldsPanel.Controls.Add(searchField.MyControl, 1, 0);
}
var myHeight = MySearchFieldsPanel.Controls.Cast<Control>().Sum(variable => variable.Height);
MyBdPanel.RowStyles[1].Height = myHeight + 40;
}
I appreciate any help
This line is a reason of all problems:
Parent.Controls.Add(AssociatedLabel);
This is bad idea if you are creating composite controls (composite = consisting from several real controls). That will cause layout problems you have experienced and more.
Instead consider either:
Utilize UserControl to create composition.
Create custom control (like you do) but without more controls. If you need label - draw it as text in OnPaint while allocating some space: fixed with margin, adjustable with some property or dynamic with measuring text.

Change ComboBox Border Color - Flash when SelectedIndex changed

I just wanted to know if in windows forms I can create a red line around the border of a combobox when its changed? Like just a flash of red and then gone again just to show that it was changed. Catch the user's eye or something. I will provide screens to represent what i would like.
If it is possible, please tell me where I can look it up to gain some information on it.
No border
Border flash on change
Border gone again after a second or two
Anytime the combobox changes, I want to flash a border to indicate it has changed.
The main idea is using a timer and drawing a border for some times. You can draw the border using different solutions. For example you can (1) draw the border on ComboBox or (2) you can draw border on Parent of ComboBox.
In the answer which I posed, I created a MyComboBox and added a FlashHotBorder method which can be called to flash border. Also I added a HotBorderColor property which can be used to set border color.
Flashing Border of ComboBox
To draw a border for ComboBox you can handle WM_Paint message of ComboBox and draw a border for control. Then to flash the border, you need to use a timer and turn on and turn off border for some times:
MyComboBox Code
I've created a FlashHotBorder method which you can call in SelectedIndexChanged event. Also if always you want to flash border when selected index changes, you can call it in OnSelectedIndexChanged. I prefer to call it in event handler. Here is the implementation:
using System.Drawing;
using System.Windows.Forms;
public class MyComboBox : ComboBox
{
int flash = 0;
private const int WM_PAINT = 0xF;
private int buttonWidth = SystemInformation.HorizontalScrollBarArrowWidth;
public Color HotBorderColor { get; set; }
private bool DrawBorder { get; set; }
Timer timer;
public MyComboBox()
{
this.HotBorderColor = Color.Red;
timer = new Timer() { Interval = 100 };
timer.Tick += new System.EventHandler(timer_Tick);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_PAINT && this.DrawBorder)
using (var g = Graphics.FromHwnd(this.Handle))
using (var p = new Pen(this.HotBorderColor))
g.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1);
}
public void FlashHotBorder()
{
flash = 0;
timer.Start();
}
void timer_Tick(object sender, System.EventArgs e)
{
if (flash < 10)
{
flash++;
this.DrawBorder = !this.DrawBorder;
this.Invalidate();
}
else
{
timer.Stop();
flash = 0;
DrawBorder = false;
}
}
protected override void Dispose(bool disposing)
{
if (disposing) { timer.Dispose(); }
base.Dispose(disposing);
}
}
Then it's enough to use this event handler for SelectedIndexChanged event of eeach combo which you want to flash:
private void myComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var combo = sender as FlatCombo;
if (combo != null)
combo.FlashHotBorder();
}
You can create an outline/draw a border outside a comboBox or any other control using the DrawRectangle method.
The border will be drawn outside the comboBox if the SelectedIndex range condition satisfies else it'll revert to it's original state with no outline.
bool changed = false;
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (changed)
{
Pen p = new Pen(Color.Red);
Graphics g = e.Graphics;
int diff = 1;
g.DrawRectangle(p, new Rectangle(comboBox1.Location.X - diff, comboBox1.Location.Y - diff, comboBox1.Width + diff, comboBox1.Height + diff));
}
}
And, I am calling the Form1_Paint event on SelectedIndexChanged event of the comboBox.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex >= 1 && comboBox1.SelectedIndex <= 9)
{
changed = true;
this.Refresh();
}
else
{
changed = false;
this.Refresh();
}
}
                    Outline                                         Without Outline
So I came up with this. It's the shortest and easiest way to do it I think. If you have any recommendation, feel free to post them or comment it. thanx for all the help :).
public partial class Form1 : Form
{
private int tick = 0;
public Form1()
{
InitializeComponent();
}
bool changed = false;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (changed == true)
{
changed = false;
this.Refresh();
}
else
{
if(tick<3)
{
timer1.Enabled = true;
timer1.Start();
}
changed = true;
this.Refresh();
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (changed)
{
Graphics g1 = e.Graphics;
int diff = 1;
Rectangle rect2 = new Rectangle(comboBox1.Location.X - diff, comboBox1.Location.Y - diff, comboBox1.Width + diff, comboBox1.Height + diff);
using (LinearGradientBrush br = new LinearGradientBrush(rect2,Color.Red,Color.Blue,LinearGradientMode.Horizontal))
{
ColorBlend color_blend = new ColorBlend();
color_blend.Colors = new Color[] { Color.Red, Color.Orange, Color.Yellow, Color.Lime, Color.Blue, Color.Indigo, Color.DarkViolet};
color_blend.Positions = new float[] { 0 / 6f, 1 / 6f, 2 / 6f, 3 / 6f, 4 / 6f, 5 / 6f, 6 / 6f };
br.InterpolationColors = color_blend;
Pen p = new Pen(br, 10);
e.Graphics.DrawRectangle(p, rect2);
}
}
else
{
Pen p = new Pen(Color.Transparent);
Graphics g = e.Graphics;
int diff = 1;
g.DrawRectangle(p, new Rectangle(comboBox1.Location.X - diff, comboBox1.Location.Y - diff, comboBox1.Width + diff, comboBox1.Height + diff));
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if(tick<3)
{
comboBox1_SelectedIndexChanged(null, null);
tick++;
}
else
{
timer1.Stop();
tick = 0;
}
}
}

How to make a borderless form draggable on a custom title bar? [duplicate]

This question already has answers here:
How to move and resize a form without a border?
(7 answers)
Closed 7 years ago.
I have created a border-less form using c# but could make the custom title bar movable so I search the internet and found this code:
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCHITTEST)
m.Result = (IntPtr)(HT_CAPTION);
}
private const int WM_NCHITTEST = 0x84;
private const int HT_CLIENT = 0x1;
private const int HT_CAPTION = 0x2;
After applying this code can click and drag my form in every inch of the form except for the title bar .
This is a good example of the movable title bar.
This is a full example
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Custom_Title_Bar
{
public partial class MainForm : Form
{
private PictureBox title = new PictureBox(); // create a PictureBox
private Label minimise = new Label(); // this doesn't even have to be a label!
private Label maximise = new Label(); // this will simulate our this.maximise box
private Label close = new Label(); // simulates the this.close box
private bool drag = false; // determine if we should be moving the form
private Point startPoint = new Point(0, 0); // also for the moving
public MainForm()
{
this.FormBorderStyle = FormBorderStyle.None;// get rid of the standard title bar
this.title.Location = this.Location; // assign the location to the form location
this.title.Width = this.Width; // make it the same width as the form
this.title.Height = 50; // give it a default height (you may want it taller/shorter)
this.title.BackColor = Color.Black; // give it a default colour (or load an image)
this.Controls.Add(this.title); // add it to the form's controls, so it gets displayed
// if you have an image to display, you can load it, instead of assigning a bg colour
// this.title.Image = new Bitmap(System.Environment.CurrentDirectory + "\\title.jpg");
// if you displayed an image, alter the SizeMode to get it to display as you want it to
// examples:
// this.title.SizeMode = PictureBoxSizeMode.StretchImage;
// this.title.SizeMode = PictureBoxSizeMode.CenterImage;
// this.title.SizeMode = PictureBoxSizeMode.Zoom;
// etc
// you may want to use PictureBoxes and display images
// or use buttons, there are many alternatives. This is a mere example.
this.minimise.Text = "Minimise"; // Doesn't have to be
this.minimise.Location = new Point(this.Location.X + 5, this.Location.Y + 5); // give it a default location
this.minimise.ForeColor = Color.Red; // Give it a colour that will make it stand out
// this is why I didn't use an image, just to keep things simple:
this.minimise.BackColor = Color.Black; // make it the same as the PictureBox
this.Controls.Add(this.minimise); // add it to the form's controls
this.minimise.BringToFront(); // bring it to the front, to display it above the picture box
this.maximise.Text = "Maximise";
// remember to make sure it's far enough away so as not to overlap our minimise option
this.maximise.Location = new Point(this.Location.X + 60, this.Location.Y + 5);
this.maximise.ForeColor = Color.Red;
this.maximise.BackColor = Color.Black; // remember, we want it to match the background
this.maximise.Width = 50;
this.Controls.Add(this.maximise); // add it to the form
this.maximise.BringToFront();
this.close.Text = "Close";
this.close.Location = new Point(this.Location.X + 120, this.Location.Y + 5);
this.close.ForeColor = Color.Red;
this.close.BackColor = Color.Black;
this.close.Width = 37; // this is just to make it fit nicely
this.Controls.Add(this.close);
this.close.BringToFront();
// now we need to add some functionality. First off, let's give those labels
// MouseHover and MouseLeave events, so they change colour
// Since they're all going to change to the same colour, we can give them the same
// event handler, which saves time of writing out all those extra functions
this.minimise.MouseEnter += new EventHandler(Control_MouseEnter);
this.maximise.MouseEnter += new EventHandler(Control_MouseEnter);
this.close.MouseEnter += new EventHandler(Control_MouseEnter);
// and we need to do the same for MouseLeave events, to change it back
this.minimise.MouseLeave += new EventHandler(Control_MouseLeave);
this.maximise.MouseLeave += new EventHandler(Control_MouseLeave);
this.close.MouseLeave += new EventHandler(Control_MouseLeave);
// and lastly, for these controls, we need to add some functionality
this.minimise.MouseClick += new MouseEventHandler(Control_MouseClick);
this.maximise.MouseClick += new MouseEventHandler(Control_MouseClick);
this.close.MouseClick += new MouseEventHandler(Control_MouseClick);
// finally, wouldn't it be nice to get some moveability on this control?
this.title.MouseDown += new MouseEventHandler(Title_MouseDown);
this.title.MouseUp += new MouseEventHandler(Title_MouseUp);
this.title.MouseMove += new MouseEventHandler(Title_MouseMove);
}
private void Control_MouseEnter(object sender, EventArgs e)
{
if (sender.Equals(this.close))
this.close.ForeColor = Color.White;
else if (sender.Equals(this.maximise))
this.maximise.ForeColor = Color.White;
else // it's the minimize label
this.minimise.ForeColor = Color.White;
}
private void Control_MouseLeave(object sender, EventArgs e)
{
// return them to their default colors
if (sender.Equals(this.close))
this.close.ForeColor = Color.Red;
else if (sender.Equals(this.maximise))
this.maximise.ForeColor = Color.Red;
else // it's the minimise label
this.minimise.ForeColor = Color.Red;
}
private void Control_MouseClick(object sender, MouseEventArgs e)
{
if (sender.Equals(this.close))
this.Close(); // close the form
else if (sender.Equals(this.maximise))
{
// maximise is more interesting. We need to give it different functionality,
// depending on the window state (Maximise/Restore)
if (this.maximise.Text == "Maximise")
{
this.WindowState = FormWindowState.Maximized; // maximise the form
this.maximise.Text = "Restore"; // change the text
this.title.Width = this.Width; // stretch the title bar
}
else // we need to restore
{
this.WindowState = FormWindowState.Normal;
this.maximise.Text = "Maximise";
}
}
else // it's the minimise label
this.WindowState = FormWindowState.Minimized; // minimise the form
}
void Title_MouseUp(object sender, MouseEventArgs e)
{
this.drag = false;
}
void Title_MouseDown(object sender, MouseEventArgs e)
{
this.startPoint = e.Location;
this.drag = true;
}
void Title_MouseMove(object sender, MouseEventArgs e)
{
if (this.drag)
{
// if we should be dragging it, we need to figure out some movement
Point p1 = new Point(e.X, e.Y);
Point p2 = this.PointToScreen(p1);
Point p3 = new Point(p2.X - this.startPoint.X,
p2.Y - this.startPoint.Y);
this.Location = p3;
}
}
} // end of the class
} // end of the namespace
If you want you can extract just the moving code and integrate it with your code, the movable Title code is just in the following Event Handlers
Title_MouseUp
Title_MouseDown
Title_MouseMove
Here is the original article for this code, you can read it for more explanation about the code
http://www.dreamincode.net/forums/topic/64981-designing-a-custom-title-bar/
The link to original article is broken

How to make image button

I was wondering how could I do this. I know I can use the button component but it has the little gray stuff around it when I give it a image. With image button how could I show another image for the hover effect
You want to create a button with no border but displays different images when the user hovers over it with the mouse? Here's how you can do it:
Add an ImageList control to your form at add two images, one for the button's normal appearance and one for when the mouse is hovering over.
Add your button and set the following properties:
FlatStyle = Flat
FlatAppearance.BorderColor (and maybe MouseOverBackColor & MouseDownBackColor) to your form's background color
ImageList = the ImageList you added to the form
ImageIndex to the index value of your normal image
Code the MouseHover and MouseLeave events for the button like this:
// ImageList index value for the hover image.
private void button1_MouseHover(object sender, EventArgs e) => button1.ImageIndex = 1;
// ImageList index value for the normal image.
private void button1_MouseLeave(object sender, EventArgs e) => button1.ImageIndex = 0;
I believe that will give you the visual effect you're looking for.
Small summary (Border, MouseDownBackColor, MouseOverBackColor)
FlatApperance
BorderColor = Black or what ever you want
BorderSize = can be set to 0
MouseDownBackColor = Transparent
MouseOverBackColor = Transparent
Text = none
For MouseDown:
// ImageList index value for the mouse down image.
private void button1_MouseDown(object sender, MouseEventArgs e) => button1.ImageIndex = 2;
You can assign the BackgroundImage property for the button. You can also use the OnMouseEnter and OnMouseExit events to change the background as per your request.
See BackgroundImage OnMouseEnter OnMouseLeave
I also needed an image button, but I wanted one like the ToolstripMenuButton.
With the correct borders and colors on hover.
So I made a custom control to do just that:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace LastenBoekInfrastructure.Controls.Controls
{
[DefaultEvent("Click")]
public class ImageButton : UserControl
{
public string ToolTipText
{
get { return _bButton.ToolTipText; }
set { _bButton.ToolTipText = value; }
}
public bool CheckOnClick
{
get { return _bButton.CheckOnClick; }
set { _bButton.CheckOnClick = value; }
}
public bool DoubleClickEnabled
{
get { return _bButton.DoubleClickEnabled; }
set { _bButton.DoubleClickEnabled = value; }
}
public System.Drawing.Image Image
{
get { return _bButton.Image; }
set { _bButton.Image = value; }
}
public new event EventHandler Click;
public new event EventHandler DoubleClick;
private ToolStrip _tsMain;
private ToolStripButton _bButton;
public ImageButton()
{
InitializeComponent();
}
private void InitializeComponent()
{
var resources = new ComponentResourceManager(typeof(ImageButton));
_tsMain = new ToolStrip();
_bButton = new ToolStripButton();
_tsMain.SuspendLayout();
SuspendLayout();
//
// tsMain
//
_tsMain.BackColor = System.Drawing.Color.Transparent;
_tsMain.CanOverflow = false;
_tsMain.Dock = DockStyle.Fill;
_tsMain.GripMargin = new Padding(0);
_tsMain.GripStyle = ToolStripGripStyle.Hidden;
_tsMain.Items.AddRange(new ToolStripItem[] {
_bButton});
_tsMain.Location = new System.Drawing.Point(0, 0);
_tsMain.Name = "_tsMain";
_tsMain.Size = new System.Drawing.Size(25, 25);
_tsMain.TabIndex = 0;
_tsMain.Renderer = new ImageButtonToolStripSystemRenderer();
//
// bButton
//
_bButton.DisplayStyle = ToolStripItemDisplayStyle.Image;
_bButton.Image = ((System.Drawing.Image)(resources.GetObject("_bButton.Image")));
_bButton.ImageTransparentColor = System.Drawing.Color.Magenta;
_bButton.Name = "_bButton";
_bButton.Size = new System.Drawing.Size(23, 22);
_bButton.Click += bButton_Click;
_bButton.DoubleClick += bButton_DoubleClick;
//
// ImageButton
//
Controls.Add(_tsMain);
Name = "ImageButton";
Size = new System.Drawing.Size(25, 25);
_tsMain.ResumeLayout(false);
_tsMain.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
void bButton_Click(object sender, EventArgs e)
{
if (Click != null)
{
Click(this, e);
}
}
void bButton_DoubleClick(object sender, EventArgs e)
{
if(DoubleClick != null)
{
DoubleClick(this, e);
}
}
public class ImageButtonToolStripSystemRenderer : ToolStripSystemRenderer
{
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e)
{
//base.OnRenderToolStripBorder(e);
}
}
}
}

Categories

Resources