李晓亮的博客

导航

C#(WinForm)常用小知识点

一)C#遍历容器中的控件
代码1:
private
List<Control> find(Control c, Type t)  //c 为容器控件,  t 为所选类型
{
     List
<Control> controls = new List<Control>();
    
foreach (Control cc in c.Controls)
     {
         
if (cc.GetType() == t)
              controls.Add(cc);
     }
    
return controls;
}

代码2:

public List<TextBox> getTextBoxList()
 {
           
try
            {
                List
<TextBox> lstText = new List<TextBox>();
                IEnumerator ier
= this.panel1.Controls.GetEnumerator();
               
while (ier.MoveNext())
                {
                   
if (ier.Current is TextBox)
                    {
                        TextBox a
= ier.Current as TextBox;
                        lstText.Add(a);
                    }
                }
               
return lstText;
            }
           
catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
           
return null;
 }

二)c#中如何得到一个文本串的宽度(以像素px为单位)

 

.NET 的 System.Drawing 空间中,Graphics 对象提供了能达到此目的的方法:MeasureString()       
public void PrintOutBox(string printStr,int printWidth,string printAlingment,System.Windows.Forms.PaintEventArgs g)
  {
            int x1 = CurrentX;
            int y1= CurrentY;
            int t_space=2;
            SizeF sf=g.MeasureString(printStr,printFont());// printFont()为返回类型为Font的方法
            Rectangle rec1 = new Rectangle(CurrentX, CurrentY, printWidth, (int)(sf.Height + t_space));
            g.DrawRectangle(Pens.Black,rec1);
            if (printAlingment == "r" | printAlingment == "R")
            {
                CurrentX = x1 + printWidth - (int)sf.Width;
                CurrentY = y1 +  (t_space / 2);
            }
            g.DrawString(printStr, printFont(), Brushes.Black, CurrentX, CurrentY);
  }

 

posted on 2010-06-30 00:35  LeeXiaoLiang  阅读(407)  评论(0编辑  收藏  举报