Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
32
Добавлен:
23.11.2019
Размер:
2.4 Mб
Скачать

Создание обработчиков событий

  1. Дважды щелкните Очистить и добавьте следующий код в созданный обработчик событий Click.

this.inkCanvas1.Strokes.Clear();

  1. Вернитесь в представление Конструктор, щелкнув правой клавишей мыши редактор кода и выбрав пункт Конструктор.

  2. Дважды щелкните Закрыть и добавьте следующий код в созданный обработчик событий Click.

this.Close();

  1. Нажмите клавишу F5 для выполнения проекта.

  2. В открывшемся приложении нарисуйте рисунок в элементе управления InkCanvas. Если допущена ошибка, можно нажать кнопку Очистить, чтобы начать заново.

  3. Нажмите кнопку Закрыть, чтобы закрыть приложение.

Designing a User Interface in Visual C#

In Visual C#, the most rapid and convenient way to create your user interface (UI) is to use the Windows Forms Designer and Toolbox.

There are three basic steps in creating all user interfaces:

  • Adding controls to the design surface.

  • Setting initial properties for the controls.

  • Writing handlers for specified events.

Although you can also create your UI by writing your own code, designers enable you to do this work much faster than is possible by manual coding.

Adding Controls

In the designer, you use the mouse to drag controls, such as buttons and text boxes, onto a design surface that represents the form. The following illustration shows a combo box that has been dragged from the Toolbox onto a form in the Windows Forms Designer.

Создание пользовательского интерфейса в Visual c#

Быстрота и удобство создания пользовательских интерфейсов в Visual C# для приложений Windows обеспечивается благодаря конструктору Windows Forms и панели элементов.

В создании пользовательских интерфейсов для приложений Windows Forms имеются три основных этапа:

  • Добавление элементов управления на поверхность разработки.

  • Установка начальных свойств для элементов управления.

  • Написание обработчиков для заданных событий.

Хотя пользовательский интерфейс можно создать, написав собственный код, с помощью конструкторов это можно сделать намного быстрее.

Добавление элементов управления

Элементы управления, такие как кнопки и текстовые поля, можно перетащить мышью на поверхность разработки, представляющую форму. На рисунке ниже показано поле со списком, которое при помощи перетаскивания из панели элементов было добавлено в форму в конструкторе Windows Forms.

As you work visually, the designer translates your actions into C# source code and writes them into a project file that is named <name>.designer.cs where <name> is the name that you gave to the form. When your application runs, that source code will position and size your UI elements so that they appear just as they do on the design surface.

При работе в визуальном режиме конструктор преобразует выполняемые действия в исходный код C# и записывает их в файл проекта с именем имя.designer.cs, где имя — имя, назначенное форме. Когда приложение будет выполнено, исходный код разместит элементы пользовательского интерфейса и скорректирует их размеры таким образом, как они отображаются на поверхности разработки.

Setting Properties

After you add a control to your form, you can use the Properties window to set its properties, such as background color and default text. The values that you specify in the Properties window are the initial values that will be assigned to that property when the control is created at run time. In many cases, those values can be accessed or changed programmatically at run time by getting or setting the property on the instance of the control class in your application. The Properties window is useful at design time because it enables you to browse all the properties, events, and methods supported on a control. For more information, see Properties Window.

Handling Events

Programs with graphical user interfaces are primarily event-driven. They wait until a user does something such as entering text into a text box, clicking a button, or changing a selection in a list box. When that occurs, the control, which is just an instance of a .NET Framework class, sends an event to your application. You have the option of handling an event by writing a special method in your application that will be called when the event is received.

You can use the Properties window to specify which events you want to handle in your code. Select a control in the designer and click the Events button, with the lightning bolt icon, on the Properties window toolbar to see its events. The following diagram shows the events button.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]