Kacper Piotrowski
Kacper Piotrowski

Reputation: 35

how to call Resize Event in C#

I'm trying to create new Button with custom event. It's new for me. I'm trying to call "Resize". I wanna create "switch" like in android.

I'm trying to do this like other existing controls. I've been doing this for 2 days and i still have nothing. I belive that you will able to help me :)

Here is my code:

    public abstract class SwitchBase : Control
    {

    private Button first;
    private Button second;

    public SwitchBase()
    {
        InitializeMySwitch();
    }

    private void InitializeMySwitch()
    {

        Controls.Add(first = new Button());
        Controls.Add(second = new Button());

        //first
        first.Text = "first";

        //second
        second.Text = "second";
        second.Location = new System.Drawing.Point(first.Location.X + first.Width, first.Location.Y);

    }


    public delegate void ChangedEventHandler(object source, EventArgs args);

    public event ChangedEventHandler Changed;

    protected virtual void OnSwitchChanged()
    {
        if (Changed != null)
            Changed(this, EventArgs.Empty);
    }

    public delegate void ResizeEventHandler(object source, EventArgs args);

    public event ResizeEventHandler Resize;

    protected virtual void OnResize()
    {
            Resize(this, EventArgs.Empty);
    }

}

public class Switch : SwitchBase
{
    public Switch()
    {

    }

    protected override void OnSwitchChanged()
    {
        base.OnSwitchChanged();
    }

    protected override void OnResize()
    {
        base.OnResize();
    }
}

In another button I change the size of my switch

Upvotes: 1

Views: 3525

Answers (1)

Theraot
Theraot

Reputation: 40170

From reading your code, I gather that by "call Resize" you mean to raise the event. What you are doing is correct... although it should be noted that by the default event implementation, it will be null if there are no subscribers...

In fact, another thread could be unsubscribing behind your back. Because of that the advice is to take a copy.

You can do that as follows:

var resize = Resize;
if (resize != null)
{
    resize(this, EventArgs.Empty)
}

It should be noted that the above code will call the subscribers to the event, but will not cause the cotrol to resize. If what you want is to change the size of your control, then do that:

this.Size = new Size(400, 200);

Or:

this.Width = 400;
this.Height = 200;

Note: I don't know what Control class you are using. In particular, if it were System.Windows.Forms.Control it already has a Resize event, and thus you won't be defining your own. Chances are you are using a Control class that doesn't even have Size or Width and Height.

Edit: System.Web.UI.Control doesn't have Resize, nor Size or Width and Height. But System.Windows.Controls.Control has Width and Height even thought it doesn't have Resize.

Upvotes: 1

Related Questions