简体   繁体   中英

How to create a Custom Image Button, made of three individual buttons and add event handler

I want to make a Custom Image Button which should be consist of three buttons with attached click event .
I tried to make a Customize button but I couldn't able attached a separate event handler .
for each button:

 class MulitButtons : UserControl
    {
        public Color bckColor1 = Color.Blue;       

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e); 

            Graphics graphics = e.Graphics; 
            RectangleF recF1 = new RectangleF(0, 0, 100, 40);
            RectangleF recF2 = new RectangleF(100, 0, 100, 40);
            RectangleF recF3 = new RectangleF(200, 0, 100, 40);   
            RectangleF[] arrRecF = { recF1, recF2, recF3 };  

            Pen pen = new Pen(Color.Black, 2);
            int fontHeight = 10;
            Font font = new Font("Arial", fontHeight);
            SolidBrush brush = new SolidBrush(bckColor1);    
            SolidBrush textBrush = new SolidBrush(Color.Black);  

            graphics.DrawRectangles(pen, arrRecF);
            graphics.DrawString(Text, font, textBrush, 10, 10);     
        }

    }


Adding event handler:

 MulitButtons objMltBtn = new MulitButtons();
 EventHandler handler= new EventHandler(but1_Click);
 objMltBtn.Click += handler;

Please help me out. Thanks.

If I understand well, you want to publish the Click events of your inner buttons.

Solution 1

This simply publishes the inner click event.

public event EventHandler Button1Click
{
    add { button1.Click += value; }
    remove { button1.Click -= value; }
}

Solution 2

If you want some control over the invoking, do it like this:

public MultiButtons()
{
    InitializeComponents();
    button1.Click += ButtonClick;
    button2.Click += ButtonClick;
    button3.Click += ButtonClick;
}

// this handles all of your clicks
private void ButtonClick(object sender, EventArgs e)
{
    if (sender == button1)
        OnButton1Click(EventArgs.Empty);
    // TODO: the other buttons...
}

public event EventHandler Button1Click;

protected virtual void OnButton1Click(EventArgs e)
{
    var handler = Button1Click;        
    if (handler != null)
        handler(this, e);
    else
        // you can call some default action if there is no event subscription
        DefaultButton1Click();
}

Update: I have just seen your comment:

I need a custom Image button with Three sections and on each section click i want to invoke an event which will perform some operation.

Just create three separate buttons next to each other and draw them in the Paint as if they were a single button. Then you can use one of the solutions above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM