воскресенье, 12 июня 2011 г.

Горизонтальная линия на c#

Как добавить на форму горизонтальную линию (как тег hr)? Есть разные способы. Один из них - создать для этого user control.

Код взял отсюда.
  1. Right Click on your project in the Solotion Explorer Window and Select Add New Item...
  2. Select UserControl on the list, select a name to the file and click Add
  3. Now make the class you created look like the code below.
  4. Build the application, the Line Separator should be available on the toolbar
namespace LineSeparator
{
    using System.Drawing;
    using System.Windows.Forms;

    public sealed partial class LineSeparator : UserControl
    {
        public LineSeparator()
        {
            InitializeComponent();

            this.Paint += this.LineSeparator_Paint;
            MaximumSize = new Size(2000, 2);
            MinimumSize = new Size(0, 2);
            Width = 350;
        }

        private void LineSeparator_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;
            g.DrawLine(Pens.DarkGray, new Point(0, 0), new Point(Width, 0));
            g.DrawLine(Pens.White, new Point(0, 1), new Point(Width, 1));
        }
    }
}
Разумеется, подкорректируйте namespace.

Если же после build'а контрол не появляется в toolbox'е, то нужно сделать следующее. Выбираем меню Tools > Options menu. Там слева ищем Windows Forms Designer (оно снизу) и ставит AutoToolboxPopulate в true. После этого нужно закрыть проект и открыть его заново. Тогда контрол должен появиться.

-

Есть и такие способы:

To simulate the line in Windows Forms use a Label control. Set its Height to 2 pixels and BorderStyle to Fixed3D. Thats all, see the example.

label1.AutoSize = false;
label1.Height = 2;
label1.BorderStyle = BorderStyle.Fixed3D;