Compiling the Code
You can compile the example at a command prompt or paste the code into a console application by using the IDE. In the latter case, you must reference the System.Drawing.dll file.
Replace "c:\test.bmp", "c:\test.jpg", "c:\test.gif" and c:\test.png
with the actual file name.
Преобразование изображений из одного формата в другой
В этом примере показана загрузка изображения и его сохранение в нескольких различных графических форматах.
Пример28
-----
Компиляция кода
Пример можно скомпилировать в командной строке либо вставить код в консольное приложение с помощью IDE. В последнем случае необходимо добавить ссылку на файл System.Drawing.dll.
Замените "c:\test.bmp", "c:\test.jpg", "c:\test.gif" and c:\test.png
фактическим именем файла.
Customizing, Displaying, and Printing Windows Forms
This topic provides links to topics that show you how to perform tasks specific to Windows Forms, such as customizing the shape and color of a form, and displaying and printing forms.
How to: Change the Background Color of a Form
This example changes the background color of a Windows Form programmatically.
Example
private void Form1_Click(object sender, EventArgs e) { this.BackColor = System.Drawing.Color.DarkBlue; } |
Compiling the Code
This example requires:
A form named Form1. Set its Click event handler to
Form1_Click
.
How to: Create a Shaped Form
The following example gives a form an elliptical shape.
Example
System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath(); shape.AddEllipse(0, 0, this.Width, this.Height); this.Region = new System.Drawing.Region(shape); |
Compiling the Code
To use this code, copy it to the Form1_Load
event handler.
The Region
property of the Form
class is an advanced member.
Настройка, отображение и печать Windows Forms
В данном разделе приводятся ссылки на разделы, содержащие сведения о выполнении определенных задач в Windows Forms, таких как настройка вида и цвета формы, отображение и печать форм.
Изменение цвета фона формы
В этом примере программно изменяется цвет фона формы Windows Forms.
Пример
private void Form1_Click(object sender, EventArgs e) { this.BackColor = System.Drawing.Color.DarkBlue; } |
Компиляция кода
Для этого примера необходимы следующие компоненты.
Форма с именем Form1. Обработчик событий Click со значением
Form1_Click
.
Создание сложной формы
В следующем примере создается форма в виде эллипса.
Пример
System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath(); shape.AddEllipse(0, 0, this.Width, this.Height); this.Region = new System.Drawing.Region(shape); |
Компиляция кода
Чтобы использовать этот код, скопируйте его в обработчик событий Form1_Load
.
Свойство Region
класса Form
является дополнительным элементом.
How to: Get a Value from Another Form
This example retrieves a value from a text box on a Windows Form and displays it in a text box on another form.
Example
// In Form1.cs. private Form2 otherForm = new Form2(); private void GetOtherFormTextBox() { textBox1.Text = otherForm.TextBox1.Text; } private void button1_Click(object sender, EventArgs e)
GetOtherFormTextBox(); } |
Compiling the Code
This example requires:
Two forms named
Form1
andForm2.
Each form contains a TextBox control namedtextBox1
.Form1
should create an instance ofForm2
and assign it tootherForm
;GetOtherFormTextBox
will copy the text intextBox1
onForm2
totextBox1
onForm1
.The Text property of
textBox1
onForm2
should be assigned a string at design-time.
Получение значения из другой формы
В этом примере извлекается значение из текстового поля в одной форме Windows Forms и отображается в текстовом поле в другой форме.
Пример29
// In Form1.cs. private Form2 otherForm = new Form2(); private void GetOtherFormTextBox() { textBox1.Text = otherForm.TextBox1.Text; } private void button1_Click(object sender, EventArgs e) { GetOtherFormTextBox(); } |
Компиляция кода
Для этого примера необходимы следующие компоненты.
Две формы с именами
Form1
andForm2.
В каждой форме содержится элемент управления TextBox с именемtextBox1
.Form1
должна создать экземплярForm2
и присвоить егоotherForm
;GetOtherFormTextBox
скопирует текст изtextBox1
, находящегося вForm2
, вtextBox1
вForm1
.Свойству Текст
textBox1
вForm2
должно быт назначено строковое значение во время разработки.
How to: Display One Form from Another
This example displays a second form from a Windows Form.
This example requires two Windows Forms named Form1 and Form2.
Form1 contains a Button control named button1.
Procedure
To create Form1
Create a Windows Forms Application, and name it Form1.
Add a Button control to the form, and name it button1.
Add the
Form2
class to the namespace, and set theClick
event handler ofbutton1
as shown in the following code.
When you click the button, Form2
will be displayed.
Example
private void button1_Click(object sender, System.EventArgs e) { Form2 frm = new Form2(); frm.Show(); } // Create Form2. public class Form2: Form { public Form2() { Text = "Form2"; } } |
Отображение одной формы из другой
Этот пример отображает вторую форму из формы Windows Forms.
Для данного примера требуются две формы Windows Forms с именами Form1 и Form2.
Form1 содержит элемент управления Button с именем "button1".
Процедура
Создание формы Form1
Создайте приложение Windows Forms и назовите его Form1.
Добавьте в форму элемент управления Button и присвойте ему имя button1.
В пространство имен добавьте класс
Form2
и задайте обработчик событийClick
дляbutton1
, как показано в следующем коде.
При нажатии кнопки будет отображена Form2
.
Пример30
---------
Creating WPF Applications
This following topics show you how to perform tasks specific to Windows Presentation Foundation (WPF) applications, such as designing a user interface with WPF controls and writing event handlers.
Designing a User Interface for a WPF Application
You can design a user interface for a Windows Presentation Foundation (WPF) application just as you can for a Windows Form application. You drag controls from the Toolbox to the design surface. The integrated development environment (IDE) is different for WPF applications. In addition to having a Properties window and Toolbox, the WPF IDE has a XAML editor. XAML is an extensible application markup language that can be used to create a user interface. The following illustration shows the location of the XAML editor.
- Введение в язык c# и .Net Framework
- Язык c#
- Архитектура платформы .Net Framework
- Creating Your First c# Application
- To create a c# application
- Создание первого приложенияC#
- Создание приложения c#
- To create a c# console application
- Создание консольного приложения c#
- To create a c# Windows application
- Создание приложений Windows Forms на c#
- Introduction to Windows Presentation Foundation
- To create a wpf application
- Создание приложения wpf c#
- To create event handlers
- Создание обработчиков событий
- Designing a User Interface in Visual c#
- Adding Controls
- Создание пользовательского интерфейса в Visual c#
- Добавление элементов управления
- Setting Properties
- Handling Events
- Задание свойств
- Обработка событий
- How to: Use Button Controls
- Использование элемента управления "Button"
- To use buttons in a program
- Использование кнопок в программе
- How to: Call a Button's Click Event Programmatically
- To use buttons in a program
- Программный вызов события нажатия кнопки
- Использование кнопок в программе
- How to: Create a Group of Radio Buttons from a String Array
- Compiling the Code
- Example
- Создание группы переключателей из массива строк
- Создание непрямоугольной кнопки
- Компиляция кода
- How to: Display Text on a Windows Form
- To display text in a label
- Отображение текста в форме Windows Forms
- Отображение текста в надписи
- How to: Use TextBox Controls to Get User Input
- Использование элемента управления "TextBox" для получения вводимых данных
- To retrieve input typed in a text box
- Извлечение введенных в текстовое поле данных
- How to: Convert the Text in a TextBox Control to an Integer
- Диалоговые окна Извлечение данных из диалогового окна
- To create the main form of your application
- To create a dialog box
- Создание основной формы приложения
- Создание диалогового окна
- Retrieving Data from a Dialog Box
- To retrieve data from a dialog box.
- Извлечение данных из диалогового окна
- How to: Browse a Folder
- To display the folder browser dialog box
- Просмотр папки
- Отображение диалогового окна обозревателя папок
- How to: Save a File to a Folder
- To display the folder browser dialog box
- Сохранение файла в папку
- Отображение диалогового окна обозревателя папок
- How to: Display a List of Fonts
- To display the font dialog box
- Отображение списка шрифтов
- Отображение диалогового окна выбора шрифта
- How to: Display an OpenFileDialog Dynamically
- Отображение цветовой палитры
- Отображение диалогового окно выбора цвета
- ListBox and ComboBox Controls
- Compiling the Code
- Отображение даты и времени в приложении
- Отображение даты с помощью элемента управления "MonthCalendar"
- To display the time by using a DateTimePicker control
- Отображение времени с помощью элемента управления "DateTimePicker"
- How to: Determine the Span Between Two Dates
- Создание настраиваемого пользовательского интерфейса
- Добавление панелей инструментов в приложение Windows Forms
- To add a set of standard toolbar button
- Добавление набора стандартных кнопок панели инструментов
- How to: Create a Tooltip for a Control
- Compiling the Code
- Compiling the Code
- Добавление элементов управления Windows Forms во время выполнения
- Компиляция кода15
- Accessing and Displaying Data
- How to: Write Class Data to an xml File
- Example
- Compiling the Code
- Compiling the Code
- Robust Programming
- Чтение xml из файла
- Пример18
- Компиляция кода
- Надежное программирование
- How to: Read Class Data from an xml File
- Example
- Compiling the Code
- Robust Programming
- Чтение данных класса из xml-файла
- Пример19
- Компиляция кода
- Compiling the Code
- Компиляция кода
- Compiling the Code
- Robust Programming
- Рисование кривой в форме
- Компиляция кода
- Надежное программирование
- How to: Draw Outlined Shapes
- Example
- Compiling the Code
- Robust Programming
- Рисование контурных фигур
- Пример23
- Компиляция кода
- Добавление файлов мультимедиа в приложение
- Внедрение проигрывателя Windows Media в форму
- Добавление элемента управления "Windows Media Player" в панель элементов.
- To add the Windows Media Player control to a Windows Form
- Добавление элемента управления "Windows Media Player" в форму Windows Forms
- How to: Play Sounds in an Application
- To play an audio file
- Воспроизведение звука в приложении
- Воспроизведение аудиофайла
- Creating and Using Bitmaps and Icons
- How to: Create a Bitmap at Run Time
- Example
- Создание и использование точечных рисунков и значков
- Создание точечного рисунка во время выполнения
- Compiling the Code
- Compiling the Code
- Создание приложений wpf
- Создание пользовательского интерфейса для приложения wpf
- To create a wpf application
- Создание приложения wpf
- Adding Controls to the wpf Window You can add controls to the wpf window by dragging them from the Toolbox. To add a control to the wpf window
- Добавление элементов управления в окно wpf
- Добавление элемента управления в окно wpf
- Common wpf Controls
- Procedure To add a control to the wpf window
- Стандартные элементы управления wpf
- Процедура Добавление элемента управления в окно wpf
- Standard wpf Controls
- Стандартные элементы управления wpf
- How to: Create Event Handlers for wpf Controls
- To create an event handler for a button
- Создание обработчиков событий для элементов управления wpf
- Создание обработчика событий для кнопки
- Connecting to Data
- How to: Connect to a Database
- To add a connection to the Northwind database
- Подключение к данным
- Подключение к базе данных
- Добавление подключения к базе данных "Northwind"
- How to: Display Related Data on a Form
- To display related data on a form
- Отображение связанных данных в форме
- Отображение связанных данных в форме
- Using linq in c# Express
- Advantages of Using linq
- Использование linq в c# Express
- Преимущества использования linq
- C# Language Enhancements that Support linq
- Расширения языка c# для поддержки linq
- Writing linq Queries
- Linq to Objects
- Написание запросов linq
- Linq to Objects
- Linq to sql
- Linq to DataSet
- Linq to xml
- Linq to sql
- Linq to DataSet
- ЯзыкC# для начинающих Структура программы c#
- "Hello World" в стиле c#
- Using Directives and Namespaces
- Comments
- Директивыusingи пространства имен
- Комментарий
- Classes
- Console Input and Output
- Консольный ввод и вывод
- Program Structure and Flow of Execution
- Windows Forms Applications
- Структура программы и ход выполнения
- Приложения Windows Forms36
- Console Applications
- Namespaces
- Консольные приложения
- Пространства имен
- Namespace Shortcuts
- Creating Your Own Namespace
- Ускоренный доступ к содержимому пространства имен
- Создание собственного пространства имен
- Example
- Classes
- Classes vs. Objects
- Классы и объекты
- Static vs. Instance Members
- Classes vs. Files
- Члены экземпляра и статические члены37
- Классы и файлы
- Encapsulation
- Инкапсуляция
- Inheritance
- Polymorphism
- Наследование
- Полиморфизм
- Constructors
- Конструкторы
- Operator Overloading
- Compiling the Code
- Имитация параметров по умолчанию
- Компиляция кода
- Переменные и константы
- Constants
- Built-in Data Types
- Константы
- Встроенные типы данных
- Using Built-in Data Types
- Типы значений и ссылочные типы
- Boxing and Unboxing
- Упаковка и распаковка
- Performance issues
- Проблемы производительности
- Operators
- Decisions and Branching
- Remarks
- Выбор и ветвление
- Foreach Loops
- Циклы foreach
- For Loops
- Working with Strings
- Доступ к отдельным знакам
- Changing Case
- Смена регистра
- Comparisons
- Сравнения
- Splitting a String into Substrings
- Разделение строки на подстроки
- Using StringBuilder
- Использование класса StringBuilder
- How to: Generate Multiline String Literals
- Массивы и коллекции
- Массивы
- Одномерные массивы
- Multidimensional Arrays
- Jagged Arrays
- Многомерные массивы
- Массивы массивов
- Using the foreach Statement
- Использование оператора foreach
- Arrays of Objects
- Массивы объектов
- How to: Declare an Array
- Compiling the Code
- Robust Programming
- Инициализация массива
- Компиляция кода
- Коллекции
- How to: Iterate Through an Array
- Compiling the Code
- Компиляция кода
- Enumerations
- Перечисления
- More Advanced Enumeration Techniques
- Try and Catch
- Обработка ошибок и исключений
- Try и Catch
- Finally Blocks
- Using Exception Handling
- You can also cause your own exceptions using the throw keyword.
- Блоки finally
- How to: Catch an Exception
- Example
- Compiling the Code
- Перехват исключения
- Компиляция кода
- .Net Framework Conceptual Overview
- Общие сведения об основных понятиях платформы .Net Framework
- Features of the Common Language Runtime
- Возможности среды clr
- .Net Framework Class Library
- Библиотека классов платформы .Net Framework