CCCP
CCCP

Reputation: 215

Use same code on another button

I'm using the exact same code multiple times and I thought that it would be quite inefficient to just copy/paste everything. Is there a way for let's say button2 to use the exact same code as button1 without copy/pasting everything?

Some of my code is very big, that's why I'm asking.

I'm aware of this for example:

    private TabPage T
    {
        get { return (t.SelectedTab); }
    }

However I have no idea how to make this work for this: (Yes, there are multiple ways to enable Full Screen mode in my application)

        if (FormBorderStyle != FormBorderStyle.None)
        {
            FormBorderStyle = FormBorderStyle.None;
            WindowState = FormWindowState.Normal;
            WindowState = FormWindowState.Maximized;
            p1.BackColor = Color.White;
            p2.BackColor = Color.White;
            TopMost = true;
            c2.Visible = false;
            Wi.Visible = false;
            t1.Visible = false;
            F.Text = "Exit Full Screen";
            t2.Text = "Exit Full Screen";
        }
        else
        {
            FormBorderStyle = FormBorderStyle.Sizable;
            if (Environment.OSVersion.Version.Build >= 7000)
            {
                if (DWM.DwmIsCompositionEnabled())
                {
                    Color c = Color.FromArgb(255, 221, 220, 220);
                    TransparencyKey = c;
                    p1.BackColor = c;
                    p2.BackColor = c;
                    MARGINS mr = new MARGINS();
                    mr.T = 1800;
                    IntPtr h = Handle;
                    int result = DwmExtendFrameIntoClientArea(h, ref mr);
                }
            }
            TopMost = false;
            Wi.Visible = true;
            t1.Visible = true;
            F.Text = "Full Screen";
            t2.Text = "Full Screen";
        }

Upvotes: 0

Views: 178

Answers (2)

Joshua Johnson
Joshua Johnson

Reputation: 87

You can also put the code in a separate method and call the method in both event handlers making no confusion about that it does and for who. they can see exactly which button calls what method or code. In this case it would be the same method.

Upvotes: 1

Servy
Servy

Reputation: 203835

Just apply the same event handler to both buttons. This can be done either through simply typing the name of the method in the events tab of the designer, or through manually adding the event handler upon construction.

It's generally a good idea in such cases to also refactor the method name into something that makes sense for both buttons to call. If clicking button2 fires button1_click some other coders might be confused. If both buttons fire a MakeFullscreen method then it's less confusing.

Upvotes: 0

Related Questions