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

Compiling the Code

This example requires:

  • A reference to the System namespace.

Robust Programming

The following conditions may cause an exception:

  • Trying to set a pixel outside the bounds of the bitmap.

// The two inner loops iterate through

// each pixel in an individual square.

for (int j = columns * colWidth; j < (columns * colWidth) + colWidth; j++)

{

for (int k = rows * rowHeight; k < (rows * rowHeight) + rowHeight; k++)

{

// Set the pixel to the correct color.

checks.SetPixel(j, k, color);

}

}

}

}

pictureBox1.Image=checks;

}

Компиляция кода

Для этого примера необходимы следующие компоненты.

  • Ссылка на пространство имен System.

Надежное программирование

Исключение может возникнуть при следующих условиях.

  • Попытка указать точку за пределами точечного рисунка.

How to: Convert Images from One Format to Another

This example demonstrates loading an image and saving it in several different graphics formats.

Example

class Program

{

static void Main(string[] args)

{

// Load the image.

System.Drawing.Image image1 = System.Drawing.Image.FromFile(@"C:\test.bmp");

// Save the image in JPEG format.

image1.Save(@"C:\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

// Save the image in GIF format.

image1.Save(@"C:\test.gif", System.Drawing.Imaging.ImageFormat.Gif);

// Save the image in PNG format.

image1.Save(@"C:\test.png", System.Drawing.Imaging.ImageFormat.Png);

}

}

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 and Form2. Each form contains a TextBox control named textBox1. Form1 should create an instance of Form2 and assign it to otherForm; GetOtherFormTextBox will copy the text in textBox1 on Form2 to textBox1 on Form1.

  • The Text property of textBox1 on Form2 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 and Form2. В каждой форме содержится элемент управления 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

  1. Create a Windows Forms Application, and name it Form1.

  2. Add a Button control to the form, and name it button1.

  3. Add the Form2 class to the namespace, and set the Click event handler of button1 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

  1. Создайте приложение Windows Forms и назовите его Form1.

  2. Добавьте в форму элемент управления Button и присвойте ему имя button1.

  3. В пространство имен добавьте класс 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.

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