Normally we dont have any event for the Drawing objects like circle, eclipse ect., so here I am trying to draw a eclipse using graphics and try to give clicking effect and handing that event.
I will be explaing the code inline, Create a Windows C# application and use following code
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms;
namespace DrawEclipse { public partial class Form1 : Form { //Declare the event handler and deligate to handle the events private delegate void EclipseClickedEventHandler(object sender); private event EclipseClickedEventHandler Eclipse_Clicked;
public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { //Initialise the Click Event for eclipse we are drawing this.Eclipse_Clicked += new EclipseClickedEventHandler(Eclipse1_Cliked); }
private void Form1_Paint(object sender, PaintEventArgs e) { //Draw eclipse in Form paint method Graphics g = e.Graphics; g.DrawEllipse(Pens.Blue, 30, 30, 50, 50); }
private void Form1_MouseDown(object sender, MouseEventArgs e) { //To give clicking effect we need to draw a similar eclipse when you // press the mouse, also check the bounds where mouse is being clicked if (e.X >= 30 && e.Y <= 80) { Graphics g = this.CreateGraphics(); //Clear the exisiting eclipse, following code draw a eclipse with form's // background color so eclipse will be cleard Pen p = new Pen(this.BackColor); g.DrawEllipse(p, 30, 30, 50, 50); // draw new eclipse g.DrawEllipse(Pens.Blue, 31, 31, 52, 52); Application.DoEvents(); //raise the clicking event Eclipse_Clicked(sender); } }
private void Form1_MouseUp(object sender, MouseEventArgs e) { //When you release the mouse button you need to draw eclipse at old position // so that will have the clicking effect. if (e.X >= 30 && e.Y <= 80) { Graphics g = this.CreateGraphics(); Pen p = new Pen(this.BackColor); g.DrawEllipse(p, 31, 31, 52, 52); g.DrawEllipse(Pens.Blue, 30, 30, 50, 50); Application.DoEvents(); Eclipse_Clicked(sender); } }
//This will be called when you click the eclipse private void Eclipse1_Cliked(object sender) { Graphics g = this.CreateGraphics(); g.DrawEllipse(Pens.Yellow, 100, 100, 50, 50); //This event will be fired when you click on eclipse //Here you can draw 2d objects } } }
Hope this helps.
SatishKumar J Microsoft MVP(ASP.NET)
|
No responses found. Be the first to respond and make money from revenue sharing program.
|