65.9K
CodeProject 正在变化。 阅读更多。
Home

具有可按比例调整大小的控件的计算器。使用 Hashtable() 存储控件的默认位置。

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (3投票s)

2003年1月5日

viewsIcon

61446

downloadIcon

663

本文档展示了如何使用 Hashtable() 存储数据,使用 foreach() 循环遍历元素集合,以及在大多数应用程序中通常可以看到的其他函数。

Sample Image - kalkulator.jpg

引言

调整不同大小和类型的控件的最佳方法是 - 存储需要调整大小的每个 Control 的默认(起始)值。当使用不同大小和位置的 Control 时,这尤其有用。可以通过执行原始对象的深度复制,或者将原始对象的参数复制到自定义对象中来实现。由于 Button 不支持 Clone(),因此需要创建自定义对象。

public class DefLocation
{

    int defW,defH,defCX,defCY; 
    public void setDefW(int dw){
       defW = dw;
    }
    public void setDefH(int dh){
       defH = dh;
    }
    public void setDefCX(int dcx){
       defCX = dcx;
    }
    public void setDefCY(int dcy){
       defCY = dcy;
    }

    public int getDefW(){return defW;}
    public int getDefH(){return defH;}
    public int getDefCX(){return defCX;}
    public int getDefCY(){return defCY;}
}

… 循环遍历 Controls,复制它们的值,并将它们存储在 HashTable hash 中,以便将来检索。

Hashtable hash = new Hashtable();
………
    public void InitDefLoc()
    {
        foreach(Control cl in Controls)
        {
            if ((cl is Button) ^ (cl is TextBox))
            {
                DefLocation dl = new DefLocation();
                dl.setDefW(cl.Width);
                dl.setDefH(cl.Height);
                dl.setDefCX(cl.Location.X);
                dl.setDefCY(cl.Location.Y);
                hash.Add(cl,dl);
            }
        }
    }

现在,每个 Button 和每个 TextBox 都有其默认参数保存在 HashTable hash 中。现在 - 最激动人心的部分 - 调整大小的例程…

private void Form1_Resize(object sender, System.EventArgs e)
{
    // calculate the resize ratio
    int widthRatio = ClientRectangle.Width * 100 / startW;
    //startW/H – hardcoded size of the application
    int heightRatio = ClientRectangle.Height * 100 / startH;
    foreach (Control ctl in Controls)
    {
        if ((ctl is Button)^(ctl is TextBox))
        {
            // for every control, access its default values stored in hash
            DefLocation dl2 = (DefLocation)hash[ctl];

            // need a new Point
            Point pnt = new Point((dl2.getDefCX() * widthRatio / 100),
                               (dl2.getDefCY() * heightRatio / 100));

            ctl.Width = dl2.getDefW() * widthRatio / 100;
            ctl.Height = dl2.getDefH() * heightRatio / 100;
            ctl.Location = pnt;
        }
    }
}
© . All rights reserved.