code_junkie

Transparent images with C# WinForms

Nov 13th, 2011
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. using System;
  2. using System.Windows.Forms;
  3. using System.Drawing;
  4.  
  5. public class TransparentControl : Control
  6. {
  7. private readonly Timer refresher;
  8. private Image _image;
  9.  
  10. public TransparentControl()
  11. {
  12. SetStyle(ControlStyles.SupportsTransparentBackColor, true);
  13. BackColor = Color.Transparent;
  14. refresher = new Timer();
  15. refresher.Tick += TimerOnTick;
  16. refresher.Interval = 50;
  17. refresher.Enabled = true;
  18. refresher.Start();
  19. }
  20.  
  21. protected override CreateParams CreateParams
  22. {
  23. get
  24. {
  25. CreateParams cp = base.CreateParams;
  26. cp.ExStyle |= 0x20;
  27. return cp;
  28. }
  29. }
  30.  
  31. protected override void OnMove(EventArgs e)
  32. {
  33. RecreateHandle();
  34. }
  35.  
  36.  
  37. protected override void OnPaint(PaintEventArgs e)
  38. {
  39. if (_image != null)
  40. {
  41. e.Graphics.DrawImage(_image, (Width / 2) - (_image.Width / 2), (Height / 2) - (_image.Height / 2));
  42. }
  43. }
  44.  
  45. protected override void OnPaintBackground(PaintEventArgs e)
  46. {
  47. //Do not paint background
  48. }
  49.  
  50. //Hack
  51. public void Redraw()
  52. {
  53. RecreateHandle();
  54. }
  55.  
  56. private void TimerOnTick(object source, EventArgs e)
  57. {
  58. RecreateHandle();
  59. refresher.Stop();
  60. }
  61.  
  62. public Image Image
  63. {
  64. get
  65. {
  66. return _image;
  67. }
  68. set
  69. {
  70. _image = value;
  71. RecreateHandle();
  72. }
  73. }
  74. }
Add Comment
Please, Sign In to add comment