Created
August 8, 2016 01:48
-
-
Save sinairv/2a605c52335be05f7205c97fc9754b39 to your computer and use it in GitHub Desktop.
LabeledPictureBox control for Windows Forms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel; | |
using System.Drawing; | |
using System.Windows.Forms; | |
// Winfows Forms picture box that shows a hovering label in the centre | |
namespace WinFormsImage | |
{ | |
public class LabeledPictureBox : PictureBox | |
{ | |
private string _labelText = "Label"; | |
private Color _labelColor = Color.White; | |
private Font _labelFont = new Font("Arial", 14F, FontStyle.Bold); | |
protected override void OnPaint(PaintEventArgs pe) | |
{ | |
base.OnPaint(pe); | |
if (!String.IsNullOrWhiteSpace(_labelText)) | |
{ | |
var labelSize = pe.Graphics.MeasureString(_labelText, _labelFont); | |
int centerX = (Size.Width - Convert.ToInt32(labelSize.Width)) / 2; | |
int centerY = (Size.Height - Convert.ToInt32(labelSize.Height)) / 2; | |
TextRenderer.DrawText(pe.Graphics, _labelText,_labelFont, | |
new Point(centerX, centerY), _labelColor); | |
} | |
} | |
[Category("Hovering Label")] | |
[Browsable(true)] | |
public string LabelText | |
{ | |
get { return _labelText; } | |
set | |
{ | |
if (!Equals(_labelText, value)) | |
{ | |
_labelText = value; | |
OnLabelTextChanged(); | |
} | |
} | |
} | |
[Category("Hovering Label")] | |
[Browsable(true)] | |
public Color LabelColor | |
{ | |
get { return _labelColor; } | |
set | |
{ | |
if (!Equals(_labelColor, value)) | |
{ | |
_labelColor = value; | |
OnLabelColorChanged(); | |
} | |
} | |
} | |
[Category("Hovering Label")] | |
[Browsable(true)] | |
public Font LabelFont | |
{ | |
get { return _labelFont; } | |
set | |
{ | |
if (!Equals(_labelFont, value)) | |
{ | |
_labelFont = value; | |
OnLabelFontChanged(); | |
} | |
} | |
} | |
public event EventHandler LabelTextChanged; | |
public event EventHandler LabelColorChanged; | |
public event EventHandler LabelFontChanged; | |
protected virtual void OnLabelTextChanged() | |
{ | |
LabelTextChanged?.Invoke(this, EventArgs.Empty); | |
Refresh(); | |
} | |
protected virtual void OnLabelColorChanged() | |
{ | |
LabelColorChanged?.Invoke(this, EventArgs.Empty); | |
Refresh(); | |
} | |
protected virtual void OnLabelFontChanged() | |
{ | |
LabelFontChanged?.Invoke(this, EventArgs.Empty); | |
Refresh(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment