C#(WinForm)常用小知識點

來源:互聯網
上載者:User

一)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);
  }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.