Ownerdrawn Button


SUBMITTED BY: Guest

DATE: Jan. 24, 2014, 7:37 p.m.

FORMAT: Text only

SIZE: 2.6 kB

HITS: 1081

  1. using System;
  2. using System.ComponentModel;
  3. using System.Drawing;
  4. using System.Windows.Forms;
  5. namespace Audentia.Common.Controls
  6. {
  7. [DefaultEvent("Click")]
  8. public sealed class Button : PictureBox
  9. {
  10. public bool Hovered { get; set; }
  11. private Timer _t;
  12. public Button()
  13. {
  14. SizeMode = PictureBoxSizeMode.AutoSize;
  15. Click += mouseclicked;
  16. _t = new Timer {Interval = 1};
  17. _t.Tick += _t_Tick;
  18. }
  19. //ToDo: Vorheriges Control speichern und abfragen
  20. private void _t_Tick(object sender, EventArgs e)
  21. {
  22. foreach (Control c in Parent.Controls)
  23. {
  24. if(c is Button)
  25. {
  26. if(c.Name!=Name)
  27. (c as Button).clicked = false;
  28. }
  29. }
  30. _t.Stop();
  31. }
  32. private void mouseclicked(object sender, EventArgs e)
  33. {
  34. _t.Start();
  35. clicked = true;
  36. }
  37. protected override void OnMouseHover(System.EventArgs e)
  38. {
  39. Cursor = Cursors.Hand;
  40. Hovered = true;
  41. Invalidate();
  42. base.OnMouseHover(e);
  43. }
  44. protected override void OnMouseLeave(System.EventArgs e)
  45. {
  46. if(!clicked)
  47. Hovered = false;
  48. Invalidate();
  49. base.OnMouseLeave(e);
  50. }
  51. private bool clicked;
  52. protected override void OnPaint(PaintEventArgs pe)
  53. {
  54. if (Image != null)
  55. {
  56. pe.Graphics.DrawImage(Hovered ? Lighten(new Bitmap(Image)) : Image, 0, 0, Image.Width, Image.Height);
  57. }
  58. else
  59. {
  60. pe.Graphics.DrawImage(ErrorImage, 0, 0, Image.Width, Image.Height);
  61. }
  62. }
  63. private Bitmap Lighten(Bitmap bitmap)
  64. {
  65. for (int i = 0; i < bitmap.Width; i++)
  66. {
  67. for (int j = 0; j < bitmap.Height; j++)
  68. {
  69. var p = bitmap.GetPixel(i, j);
  70. var pp = Color.FromArgb(150, p);
  71. if (p.A > 0)
  72. bitmap.SetPixel(i, j, pp);
  73. }
  74. }
  75. return bitmap;
  76. }
  77. }
  78. }

comments powered by Disqus