.NET开发

本类阅读TOP10

·NHibernate快速指南(翻译)
·vs.net 2005中文版下载地址收藏
·【小技巧】一个判断session是否过期的小技巧
·VB/ASP 调用 SQL Server 的存储过程
·?dos下编译.net程序找不到csc.exe文件
·通过Web Services上传和下载文件
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·VB.NET实现DirectDraw9 (2) 动画
·VB.NET实现DirectDraw9 (1) 托管的DDraw
·建站框架规范书之——文件命名

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
如何禁止调整自定义控件的尺寸?

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

  有时我们在自定义控件时,出于某种原因的考虑(比如:防止在设计时误操作),想禁止调整自定义控件的尺寸(Height Width)。最初我是这样实现的,这也是较简单的方法:

public class MyButton : System.Windows.Forms.Button

{

... ...

 

    protected override void OnResize(EventArgs e)

    {

        this.Height = 23;

        this.Width = 75;

    }

}

  但是我对这样的效果不太满意,要是能实现像TextBox那样,在设计时上下边缘的小方块是灰的,而左右边缘的小方块是白的(表示无法调整其Height),那该有多酷!经过一番研究和到CSDN上求助,终于解决了此问题,效果如下图所示:

 

 

现在将代码整理出来,希望能对大家有所帮助。

 

1、建立自定义控件设计器类。

/// <summary>

/// 自定义控件设计器类

/// </summary>

public class MyButtonDesigner : System.Windows.Forms.Design.ControlDesigner

{

    public MyButtonDesigner()

    {

    }

 

    public override SelectionRules SelectionRules

    {

        get

        {

//不允许调整控件的高度,具体说明详见MSDN

            SelectionRules rules = SelectionRules.Visible | SelectionRules.Moveable |

                SelectionRules.LeftSizeable | SelectionRules.RightSizeable;

 

            return rules;

        }

    }

}

 

2、给自定义控件类添加属性,将该控件类与上面定义的设计器类关联起来。

[Designer(typeof(MyButtonDesigner))]

public class MyButton : System.Windows.Forms.Button

{

... ...

}

 

经过以上处理,就实现了上述效果。不过如果再仔细研究一下,你会发现这只在设计时有效,而在运行时,还是能够改变该控件的高度。如何避免这个问题呢?请在相应位置加入以下代码(如有不清楚的地方请查阅MSDN)。

public class MyButton : System.Windows.Forms.Button

{

... ...

 

    protected override void SetBoundsCore(int x, int y, int width, int height,

        BoundsSpecified specified)

    {

        base.SetBoundsCore(x, y, width, 23, specified);

    }

}

 

最后提醒大家一下:要成功完成编译,必须添加System.Design引用,并在文件头部加上:

using System.Windows.Forms.Design;

 




相关文章

相关软件