Партнерка на США и Канаду по недвижимости, выплаты в крипто
- 30% recurring commission
- Выплаты в USDT
- Вывод каждую неделю
- Комиссия до 5 лет за каждого referral
Новосибирский государственный технический университет
Кафедра вычислительной техники
Лабораторная работа 3
по дисциплине «Технология программирования и разработка
Тема: «РАЗРАБОТКА GUI. СОЗДАНИЕ SDI-ПРИЛОЖЕНИЙ
ОБРАБОТКА СОБЫТИЙ»
Группа: АВТ-910
Студент:
Преподаватель:
Новосибирск 2011
Примеры кода
Пример 2. Два обработчика событий для MouseClick
namespace lab3 {
public partial class Form1 : Form {
float x, y;
// координаты
Brush pStdBrush;
// Кисть
Graphics poGraphics;
public Form1() {
x = 10; y = 20;
pStdBrush = new SolidBrush(Color. Black);
poGraphics = this. CreateGraphics();
this. Text = "Программа 1";
this. Show();
// добавление обработчиков событий нажатия кнопки мыши
this. MouseClick += new MouseEventHandler(this. Form1_MouseClick);
this. MouseClick += new MouseEventHandler(this. ShowClick);
// вывод строки в позиции x, y
poGraphics. DrawString("Hello, Window Forms", this. Font, pStdBrush, x, y);
}
private void Form1_MouseClick(object sender, MouseEventArgs e) {
x = (float)e. X; y = (float)e. Y; // получение координат мыши
// вывод строки в позиции x, y
poGraphics. DrawString("Hello, Window Forms", this. Font, pStdBrush, x, y);
}
void ShowClick(object pSender, MouseEventArgs e) {
MessageBox. Show("Mouse clicked!!'");
}
}
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application. EnableVisualStyles();
Application. SetCompatibleTextRenderingDefault(false);
*****n(new Form1());
}
}
}

Пример 3. Обработка событий от правой и левой кнопки мыши
namespace lab3 {
public partial class Form1 : Form {
float x, y;
// координаты
Brush pStdBrush;
// Кисть
Graphics poGraphics;
public Form1() {
x = 10; y = 20;
pStdBrush = new SolidBrush(Color. Black);
poGraphics = this. CreateGraphics();
this. Text = "Программа 1";
this. Show();
// добавление обработчиков событий нажатия кнопки мыши
this. MouseClick += new MouseEventHandler(this. Form1_MouseClick);
this. MouseClick += new MouseEventHandler(this. ShowClick);
// вывод строки в позиции x, y
poGraphics. DrawString("Hello, Window Forms", this. Font, pStdBrush, x, y);
}
private void Form1_MouseClick(object sender, MouseEventArgs e) {
// если левая кнопка
if (e. Button == System. Windows. Forms. MouseButtons. Left) {
x = (float)e. X; y = (float)e. Y;
poGraphics. DrawString("Hello, Window Forms", this. Font, pStdBrush, x, y);
}
}
void ShowClick(object pSender, MouseEventArgs e) {
// если правая кнопка
if (e. Button == System. Windows. Forms. MouseButtons. Right)
MessageBox. Show("Mouse clicked!!'");
}
}
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application. EnableVisualStyles();
Application. SetCompatibleTextRenderingDefault(false);
*****n(new Form1());
}
}
}

Пример 4. Компоненты
using System;
using System. Collections. Generic;
using ponentModel;
using System. Data;
using System. Drawing;
using System. Linq;
using System. Text;
using System. Windows. Forms;
namespace lab3 {
public partial class SocOpros : Form {
public SocOpros() {
InitializeComponent();
}
private void Btnyes_Click(object sender, EventArgs e) {
MessageBox. Show("Мы и не сомневались, что Вы так думаете!");
}
//В обработчике связываем движение мыши с координатами кнопки
//и устанавливаем координаты, куда она будет возвращаться, если во
//время своего движения выйдет за указанную область
private void Btnno_MouseMove(object sender, MouseEventArgs e) {
Btnno. Top -= e. Y; Btnno. Left += e. X;
if (Btnno. Top < -10 || Btnno. Top > 100) Btnno. Top = 60;
if (Btnno. Left < -80 || Btnno. Left > 250) Btnno. Left = 120;
}
private void MenuExit_Click(object sender, EventArgs e) {
Close(); //закрытие формы
}
private void SocOpros_FormClosing(object sender, FormClosingEventArgs e) {
//вывод диалога вопроса с кнопками Yes No
if (MessageBox. Show("Do you want to close", "SocOpros",
MessageBoxButtons. YesNo, MessageBoxIcon. Question)
== System. Windows. Forms. DialogResult. Yes)
//если выбрано Yes выйти из приложения
Application. Exit();
}
}
}

Пример 5. Диалоговые окна
namespace lab3 {
class Hotel {
public Hotel(String city, String name, int r, double m) {
City = city; HotelName = name;
Rooms = r; Rate = m;
}
public String City, HotelName;
public int Rooms;
public double Rate;
}
}
namespace lab3 {
public partial class AddHotelDialog : Form {
public AddHotelDialog() {
InitializeComponent();
}
public String City {
get { return txtCity. Text; }
set { txtCity. Text = value; }
}
public String HotelName {
get { return (txtHotelName. Text); }
set { txtHotelName. Text = value; }
}
public int Rooms {
get { return Convert. ToInt32(txtNumberRooms. Text); }
set { txtNumberRooms. Text = value. ToString(); }
}
public double Rate {
get { return Convert. ToDouble(txtRate. Text); }
set { txtRate. Text = value. ToString(); }
}
private void cmdOk_Click(object sender, EventArgs e) {
Close();
}
}
}
namespace lab3 {
public partial class AdminForm : Form {
public AdminForm() {
InitializeComponent();
}
ArrayList list = new ArrayList();
private void button1_Click(object sender, EventArgs e) {
AddHotelDialog dlg = new AddHotelDialog();
dlg. ShowDialog();
if (dlg. HotelName!= "") {
label1.Text = dlg. City;
label2.Text = dlg. HotelName;
label3.Text = dlg. Rooms. ToString();
label4.Text = dlg. Rate. ToString();
String s = dlg. City + ","
+ dlg. HotelName + ","
+ dlg. Rooms. ToString() + ","
+ dlg. Rate. ToString();
hotellist. Items. Add(s);
Hotel ob = new Hotel(dlg. City, dlg. HotelName, dlg. Rooms, dlg. Rate);
list. Add(ob);
} else {
MessageBox. Show("Введите данные", "Hotel Broker Administration",
MessageBoxButtons. OK, MessageBoxIcon. Exclamation);
return;
}
}
private void button2_Click(object sender, EventArgs e) {
if (MessageBox. Show("Do you want to close", "Warning",
MessageBoxButtons. YesNo, MessageBoxIcon. Question)
== System. Windows. Forms. DialogResult. Yes) {
Application. Exit();
}
}
private void AdminForm_Load(object sender, EventArgs e) {
Hotel ob1 = new Hotel("Москва", "Россия", 200, 1500);
list. Add(ob1);
Hotel ob2 = new Hotel("Москва", "Прага", 200, 3000);
list. Add(ob2);
Hotel ob3 = new Hotel("Новосибирск", "Объ", 150, 1500);
list. Add(ob3);
Hotel ob4 = new Hotel("Новосибирск", "Тратата", 300, 1200);
list. Add(ob4);
hotellist. Items. Clear();
if (list == null) { return; }
foreach (Hotel hotel in list) {
// строка для записи в элемент ListBox hotellist
String city = hotel. City. Trim();
String name = hotel. HotelName. Trim();
String rooms = hotel. Rooms. ToString();
String rate = hotel. Rate. ToString();
String str = city + "," + name + "," + rooms + "," + rate;
hotellist. Items. Add(str);
}
}
private void hotellist_SelectedIndexChanged(object sender, EventArgs e) {
if (hotellist. SelectedIndex!= -1) {
String selected = hotellist. SelectedItem. ToString();
String[] fields;
fields = selected. Split(','); // поля разбить;
label1.Text = fields[0];
label2.Text = fields[1];
label3.Text = fields[2];
label4.Text = fields[3];
} else { label1.Text = ""; }
}
}
}

1.Задание
1. Создать учебные примеры (программы 2–5) и разобрать принцип
их работы. Поместите в отчет примеры работы программ, их код с
комментариями.
2. Создать SDI-приложение (Single Document Interface, одно-
документный интерфейс) с элементами ввода и отображения полей
класса из задания к лабораторной работе 2. Для этого используйте раз-
личные элементы управления: текстовые поля, списки, независимые и
радиокнопки, а также панели и менеджеры компоновки.
3. Ввод новых данных осуществлять через дополнительную диало-
говую форму.
4. При изменении данных запрашивать подтверждение через окно
диалога. В случае неполных данных сообщать об ошибке.
5. Объекты сохранять в коллекции.
6. Реализовать просмотр всей коллекции объектов через список.
Для редактирования выбранного объекта создать дополнительную
форму модального диалога.
7. Добавить на форму меню, позволяющее работать с пунктами:
добавить, просмотреть, удалить, редактировать, справка.
8. Дублировать основные операции панелью инструментов.
2.Результат работы
Main форма

Выбор типа объекта

Заполнение журнала. Исключение на пустое название

Заполнение журнала. Исключение на пустого автора

Добавлен новый объект в список Main формы

Форма просмотра журнала

3.Исходный текст программы:
MainForm
using System;
using System. Collections. Generic;
using ponentModel;
using System. Data;
using System. Drawing;
using System. Linq;
using System. Text;
using System. Windows. Forms;
using print;
namespace printing
{
public partial class MainForm : Form
{
private List<Printing> printings = new List<Printing>();
public MainForm()
{
InitializeComponent();
listViewPrintings. Columns. Add("Title", 0, HorizontalAlignment. Center);
listViewPrintings. Columns. Add("Writer", 0, HorizontalAlignment. Center);
Test();
}
public void Test()
{
Printing objetcs0 = new Journal("fgf", "23rtfgf", 120, 256, 100);
objetcs0.addContentItem("1. Ololo", 3);
objetcs0.addContentItem("2. Rofl", 33);
objetcs0.addContentItem("3. Facepalm", 67);
Printing objetcs1 = new Book("C# 4.0", "Herbert Schildt", 430, 2011, 1056);
objetcs1.addContentItem("1. Ololo", 3);
Printing objetcs2 = new Journal("За рулём!", "2011", 150, 314, 124);
objetcs2.addContentItem("1. Nissan GT-R", 15);
objetcs2.addContentItem("2. Новый Gofl", 29);
objetcs2.addContentItem("3. Гонки по бездорожью...", 77);
printings. AddRange(new[] { objetcs0, objetcs1, objetcs2 });
printings. ForEach(AddMenuItem);
}
/// <summary>
/// Добаление объекта в список
/// </summary>
/// <param name="printing"></param>
private void AddMenuItem(Printing printing)
{
var item = new ListViewItem(printing. Title);
item. SubItems. Add(printing. Writer);
listViewPrintings. Items. Add(item);
}
/// <summary>
/// выход
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void close_Click(object sender, EventArgs e)
{
Application. Exit();
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
Type select = new Type();
DialogResult res = select. ShowDialog();
if (res == DialogResult. OK)
{
int printType = select. GetType();
Printing printing = ShowInsertDialog(printType);
if (printing!= null)
{
printings. Add(printing);
AddMenuItem(printing);
RefreshListView();
}
}
}
/// <summary>
/// Выбор типа объекта при добавлении
/// </summary>
/// <param name="printType"></param>
/// <returns></returns>
private Printing ShowInsertDialog(int printType)
{
PrintingDialog printDialog;
if (printType == 1)
{
printDialog = new BookDialog();
}
else if (printType == 2)
{
printDialog = new JournalDialog();
}
else
{
MessageBox. Show("ERROR", "Error", MessageBoxButtons. OK, MessageBoxIcon. Error);
return null;
}
return printDialog. ShowDialog(this) == DialogResult. Cancel? null : printDialog. Printing;
}
/// <summary>
/// Изменение объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void editToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (listViewPrintings. SelectedIndices. Count == 0)
{
MessageBox. Show("Select object");
return;
}
int selected = listViewPrintings. SelectedIndices[0];
Printing selectedPrint = printings[selected];
ShowEditDialog(selectedPrint);
RefreshListView();
}
/// <summary>
/// Обновление списка
/// </summary>
private void RefreshListView()
{
listViewPrintings. Items. Clear();
printings. ForEach(AddMenuItem);
}
/// <summary>
/// Выбор формы заполнения
/// </summary>
/// <param name="selectedPrint"></param>
private void ShowEditDialog(Printing selectedPrint)
{
PrintingDialog printDialog;
if (selectedPrint is Book)
{
printDialog = new BookDialog(selectedPrint);
}
else if (selectedPrint is Journal)
{
printDialog = new JournalDialog(selectedPrint);
}
else
{
MessageBox. Show("Unknown type", "Error", MessageBoxButtons. OK, MessageBoxIcon. Error);
return;
}
printDialog. ShowDialog(this);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ViewObj_Click(object sender, MouseEventArgs e)
{
int selected = listViewPrintings. SelectedIndices[0];
Printing selectedPrint = printings[selected];
ShowViewForm(selectedPrint);
}
/// <summary>
/// Выбор формы показа
/// </summary>
/// <param name="selectedPrint"></param>
private void ShowViewForm(Printing selectedPrint)
{
PrintingView printView;
if (selectedPrint is Book)
{
printView = new BookVeiw(selectedPrint);
}
else if (selectedPrint is Journal)
{
printView = new JournalVeiw(selectedPrint);
}
else
{
MessageBox. Show("Unknown type", "Error", MessageBoxButtons. OK, MessageBoxIcon. Error);
return;
}
printView. ShowDialog(this);
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listViewPrintings. SelectedIndices. Count == 0)
{
MessageBox. Show("Select object");
return;
}
int selected = listViewPrintings. SelectedIndices[0];
var confirmResult = MessageBox. Show("Do you want to delete this object?", "Confirmation dialog",
MessageBoxButtons. YesNo, MessageBoxIcon. Question);
if (confirmResult == DialogResult. Yes)
{
printings. RemoveAt(selected);
listViewPrintings. Items. RemoveAt(selected);
}
}
private void TileClick(object sender, EventArgs e)
{
listViewPrintings. View = View. Tile;
}
private void ListClick(object sender, EventArgs e)
{
listViewPrintings. View = View. List;
}
private void MainForm_Load(object sender, EventArgs e)
{
}
}
}
Type
using System;
using System. Collections. Generic;
using ponentModel;
using System. Data;
using System. Drawing;
using System. Linq;
using System. Text;
using System. Windows. Forms;
namespace printing
{
public partial class Type : Form
{
private RadioButton _selected;
public Type()
{
InitializeComponent();
}
private void Book_CheckedChanged(object sender, EventArgs e)
{
_selected = sender as RadioButton;
}
private void Journal_CheckedChanged(object sender, EventArgs e)
{
_selected = sender as RadioButton;
}
public int GetType()
{
//ShowDialog(parent);
if (_selected == book)
return 1;
if (_selected == journal)
return 2;
return 0;
}
private void Ok_Click(object sender, EventArgs e)
{
//Close();
}
private void Cancel_Click(object sender, EventArgs e)
{
//Close();
}
private void Type_Load(object sender, EventArgs e)
{
}
}
}
PrintingDialog
using System;
using System. Collections. Generic;
using ponentModel;
using System. Data;
using System. Drawing;
using System. Linq;
using System. Text;
using System. Windows. Forms;
using print;
namespace printing
{
public partial class PrintingDialog : Form
{
public PrintingDialog()
{
InitializeComponent();
}
public Printing Printing { get; set;}
/// <summary>
/// Конструктор для редактирования объекта
/// </summary>
/// <param name="Print"></param>
public PrintingDialog (Printing printing)
{
InitializeComponent();
Printing = printing;
FromContent();
}
public void FromContent()
{
Title. Text = Printing. Title;
Writer. Text = Printing. Writer;
Cost. Value = (decimal)Printing. Cost;
for (int i = 0; i < Printing. GetContentsLenght(); i++)
{
Contents. Items. Add(Printing. Contents[i]);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
int listSize = Contents. Items. Count;
string content = Description. Text + "......" + Page. Value. ToString();
Contents. Items. Add(content);
Description. Clear();
}
private void buttonDelete_Click(object sender, EventArgs e)
{
Contents. Items. RemoveAt(Contents. SelectedIndex);
}
private void buttonCancel_Click(object sender, EventArgs e)
{
Close();
}
protected bool FillPrintingCommon()
{
try
{
Printing. Title = Title. Text;
Printing. Writer = Writer. Text;
Printing. Cost = (float)Cost. Value;
Printing. Contents = new List<string>();
for (int i = 0; i < Contents. Items. Count; i++)
{
Printing. addContentItemFromString(Contents. Items[i].ToString());
}
return true;
}
catch (MyException e)
{
MessageBox. Show(e. Message, "Error", MessageBoxButtons. OK, MessageBoxIcon. Error);
}
catch (Exception e)
{
MessageBox. Show(e. Message, "Error", MessageBoxButtons. OK, MessageBoxIcon. Error);
}
return false;
}
private void PrintingDialog_Load(object sender, EventArgs e)
{
}
protected virtual void buttonOk_Click(object sender, EventArgs e)
{
}
}
}
BookDialog
using System;
using System. Collections. Generic;
using ponentModel;
using System. Data;
using System. Drawing;
using System. Text;
using System. Windows. Forms;
using print;
namespace printing
{
public partial class BookDialog : printing. PrintingDialog
{
public BookDialog()
{
InitializeComponent();
Printing = new Book();
}
public BookDialog(Printing printing)
: base(printing)
{
InitializeComponent();
FromContentBook();
}
private void FromContentBook()
{
var printing = (Book)Printing;
NumberOfPages. Value = printing. Pages;
Year. Value = printing. Year;
}
protected override void buttonOk_Click(object sender, EventArgs e)
{
bool isFilled = FillPrintingCommon();
if (isFilled)
{
try
{
var printing = (Book)Printing;
printing. Pages = (int)NumberOfPages. Value;
printing. Year = (int)Year. Value;
}
catch (MyException exc)
{
MessageBox. Show(exc. Message, "Error", MessageBoxButtons. OK, MessageBoxIcon. Error);
return;
}
catch (Exception exc)
{
MessageBox. Show(exc. Message, "Error", MessageBoxButtons. OK, MessageBoxIcon. Error);
return;
}
DialogResult = DialogResult. OK;
Close();
}
}
private void BookDialog_Load(object sender, EventArgs e)
{
}
private void Year_ValueChanged(object sender, EventArgs e)
{
}
}
}
JournalDialog
using System;
using System. Collections. Generic;
using ponentModel;
using System. Data;
using System. Drawing;
using System. Text;
using System. Windows. Forms;
using print;
namespace printing
{
public partial class JournalDialog : printing. PrintingDialog
{
public JournalDialog()
{
InitializeComponent();
Printing = new Journal();
}
public JournalDialog(Printing printing):base(printing)
{
InitializeComponent();
FromContentJournal();
}
private void FromContentJournal()
{
var printing = (Journal)Printing;
NumberOfPages. Value = printing. Pages;
Number. Value = printing. Number;
}
protected override void buttonOk_Click(object sender, EventArgs e)
{
bool isFilled = FillPrintingCommon();
if (isFilled)
{
try
{
var printing = (Journal)Printing;
printing. Pages = (int)NumberOfPages. Value;
printing. Number = (int)Number. Value;
}
catch (MyException exc)
{
MessageBox. Show(exc. Message, "Error", MessageBoxButtons. OK, MessageBoxIcon. Error);
return;
}
catch (Exception exc)
{
MessageBox. Show(exc. Message, "Error", MessageBoxButtons. OK, MessageBoxIcon. Error);
return;
}
DialogResult = DialogResult. OK;
Close();
}
}
private void JournalDialog_Load(object sender, EventArgs e)
{
}
}
}
PrintingView
using System;
using System. Collections. Generic;
using ponentModel;
using System. Data;
using System. Drawing;
using System. Linq;
using System. Text;
using System. Windows. Forms;
using print;
namespace printing
{
public partial class PrintingView : Form
{
public Printing Print { get; set; }
public PrintingView()
{
InitializeComponent();
}
public PrintingView(Printing printing)
{
InitializeComponent();
Print = printing;
FromContent();
}
public void FromContent()
{
Title. Text = Print. Title;
Writer. Text = Print. Writer;
Cost. Text = Print. Cost. ToString();
int n = Print. GetContentsLenght();
for (int i = 0; i < n; i++)
{
Contents. Items. Add(Print. Contents[i]);
}
}
private void buttonClose_Click(object sender, EventArgs e)
{
Close();
}
private void PrintingView_Load(object sender, EventArgs e)
{
}
}
}
BookView
using System;
using System. Collections. Generic;
using ponentModel;
using System. Data;
using System. Drawing;
using System. Text;
using System. Windows. Forms;
using print;
namespace printing
{
public partial class BookVeiw : printing. PrintingView
{
public BookVeiw()
{
InitializeComponent();
}
public BookVeiw(Printing printing)
: base(printing)
{
InitializeComponent();
FromContentBook();
}
private void FromContentBook()
{
var printing = (Book)Print;
NumberOfPages. Text = printing. Pages. ToString();
Year. Text = printing. Year. ToString();
}
private void BookVeiw_Load(object sender, EventArgs e)
{
}
}
}
JournalView
using System;
using System. Collections. Generic;
using ponentModel;
using System. Data;
using System. Drawing;
using System. Text;
using System. Windows. Forms;
using print;
namespace printing
{
public partial class JournalVeiw : printing. PrintingView
{
public JournalVeiw()
{
InitializeComponent();
}
public JournalVeiw(Printing printing):base(printing)
{
InitializeComponent();
FromContentJournal();
}
private void FromContentJournal()
{
var printing = (Journal)Print;
NumberOfPages. Text = printing. Pages. ToString();
Number. Text = printing. Number. ToString();
}
private void JournalVeiw_Load(object sender, EventArgs e)
{
}
}
}
Program. cpp
using System;
using System. Collections. Generic;
using System. Linq;
using System. Windows. Forms;
namespace printing
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application. EnableVisualStyles();
Application. SetCompatibleTextRenderingDefault(false);
*****n(new MainForm());
}
}
}
Вывод
В ходе данной лабораторной работе я научился применять механизм событий, создавать графический интерфейс при помощи Windows Forms в среде Visual Studio, ознакомился с имеющимися компонентами, формами, их свойствами и событиями, научился создавать диалоговые окна и связывать их между собой.


