简体   繁体   中英

Windows Forms: How to extend a button?

How can I extend a Button?

I want a Button that has an additional property IsSwitchOffable.

Do I have to write an extra custom control?

EDIT: I want that the button is usable as a standard WindowsFormsButton.

This includes that I can add the button at design time!

Extending a button control is no different then extending any class in C#. Simply do the following:

class ToggleButton : Button {
// Add your extra code
}

You need to create a class that inherits the System.Windows.Forms.Button class and adds your property and associated behavior.

After compiling your project, your new class will appear in the toolbox.

I know this is old and has been answered - however, Why make life difficult?

Each control has a Tag property which you can easily set to IsSwitchedOffable - or better English CanBeDisabled

Far easier.

In my puzzle application 2d button's location is to be changed... So i need extra facilities...

My button ButObj extends Button class

Public Class ButObj : Button
         { 
            Point initloc;
          Public ButObj(Point loc)  

 {   this.Location=initloc=loc ;   }
           Public bool isNearto(ButObj X)
               { 
                 if (this.Location.X==X.Location.X || this.Location.Y==X.Location.Y)
                   return true;
        else  return false;
               }
           Public bool isSettled()
             {
                if(this.Location==initloc)
                   return true ;
                else return false;
             }
         Public void Replace (ButObj X)
     {
           Point temp ;
             temp=this.Location;
       this.Location=X.Location;
    X.Location=temp;
    }
         }

Following code is written in form 1_load ()

ButObj[ ][ ] B=new ButObj[4][4];
   char c='A';
    for (int i=0;i<4;i++)
      for (int j=0;j<4;j++)
       {   B[i][j]=new ButObj(new Point (i*100+10,j*100+10));
B[j][i].Text = ""+c++;
B[i][j].Font =new Font ("Arial", 24);
this.Controls.Add (B[i][j]);

B[i][j].MouseClick += new MouseEventHandler(MouseClick); }

Coding in mouse click event

private void MouseClick(Object sender, EventArgs e)
    {
       ButObj b=(ButObj)sender;
       if (b.isNearto(B[3][3]))
         b.Replace(B[3][3]);
\\ checking after replace
     if(AllSolved());\\game over
     }

bool AllSolved()
      {
         for (int i=0;i<4;i++)
           for (int j=0;j<4;j++)
             if (!B[i][j].isSettled)
               return false ;
        return true;
      }

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