close

Вход

Забыли?

вход по аккаунту

?

Reports 6

код для вставкиСкачать
МИНИСТЕРСТВО ОБРАЗОВАНИЯ И НАУКИ РЕСПУБЛИКИ БЕЛАРУСЬ
БЕЛОРУССКИЙ НАЦИОНАЛЬНЫЙ ТЕХНИЧЕСКИЙ УНИВЕРСИТЕТ
Факультет информационных технологий и робототехники (ФИТР)
Кафедра программного обеспечения вычислительной техники
и автоматизированных систем
О Т Ч Е Т
ПО ЛАБОРАТОРНОЙ РАБОТЕ №7
"Использование LINQ to Objects"
по курсу:
" ОБЪЕКТНО-ОРИЕНТИРОВАННОЕ ПРОГРАММИРОВАНИЕ"
Выполнил: Студент: Ермакович А.А.
Гурченок И.В.
Гр. 107321
Проверил: Ст. пр. Радкевич А.С.
Минск - 2013
ЛАБОРАТОРНАЯ РАБОТА №7
Использование LINQ to Objects
Индивидуальное задание:
Результаты выполнения программы: Рисунок 1 - Выполнение приложения
Выводы:
1) Любой поток в C# это функция. Функции не могут быть сами по себе, они обязательно являются методами класса. Поэтому, что бы создать отдельный поток, нам понадобится класс с необходимым методом. Самый простой вариант метода возвращает void и не принимает аргументов.
2) Метод Invoke() выполняет указанный делегат в том потоке, которому принадлежит базовый дескриптор окна элемента управления.
ПРИЛОЖЕНИЕ
Листинг исходного кода программы:
Текст консольного приложения:
using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace PrLab1
{
class MyForm : Form //класс родительского окна
{
ToolStrip t1 = new ToolStrip();
ToolStripButton tb1 = new ToolStripButton();
ToolStripButton tb2 = new ToolStripButton();
ToolStripButton tb3 = new ToolStripButton();
ToolStripButton tb4 = new ToolStripButton();
ToolStripSeparator ts1 = new ToolStripSeparator();
ToolStripMenuItem tm1 = new ToolStripMenuItem();
ToolStripMenuItem tm2 = new ToolStripMenuItem();
ToolStripMenuItem tm3 = new ToolStripMenuItem();
ToolStripMenuItem tm4 = new ToolStripMenuItem();
ToolStripMenuItem tm5 = new ToolStripMenuItem();
ToolStripMenuItem tm6 = new ToolStripMenuItem();
ToolStripMenuItem tm7 = new ToolStripMenuItem();
ToolStripMenuItem tm8 = new ToolStripMenuItem();
ToolStripMenuItem tm9 = new ToolStripMenuItem();
ToolStripMenuItem tm10 = new ToolStripMenuItem();
ToolStripMenuItem tm11 = new ToolStripMenuItem();
ToolStripMenuItem tm12 = new ToolStripMenuItem();
ToolStripMenuItem tm13 = new ToolStripMenuItem();
ToolStripMenuItem tm14 = new ToolStripMenuItem();
MenuStrip m1 = new MenuStrip();
StatusStrip ss = new StatusStrip();
ToolStripStatusLabel tss1 = new ToolStripStatusLabel();
ToolStripStatusLabel tss2 = new ToolStripStatusLabel();
ColorDialog cd1 = new ColorDialog();
ColorDialog cd2 = new ColorDialog();
int VarWidthLine = 1; //толщина линии
public string ShapeName { get; set; }
public MyForm() //конструктор формы
{
Text = "Micro paint";
Height = 450;
Width = 640;
tb1.Click += new EventHandler(tb1_Click);
tm2.Click += new EventHandler(tb1_Click);
tb2.Click += new EventHandler(tb2_Click);
tm3.Click += new EventHandler(tb2_Click);
tb3.Click += new EventHandler(tb3_Click);
tm4.Click += new EventHandler(tb3_Click);
tm5.Click += new EventHandler(tm5_Click);
tm7.Click += new EventHandler(tm7_Click);
tm8.Click += new EventHandler(tm8_Click);
tm9.Click += new EventHandler(tm9_Click);
tm10.Click += new EventHandler(tm10_Click);
tm12.Click += new EventHandler(tm12_Click);
tm13.Click += new EventHandler(tm12_Click);
tm14.Click += new EventHandler(tm12_Click);
tb4.Click += new EventHandler(tm10_Click);
t1.Parent = this;
m1.Parent = this;
ss.Parent = this;
m1.Items.Add(tm1);
m1.Items.Add(tm6);
m1.Items.Add(tm11);
m1.Items.Add(tm10);
tm1.Text = "File";
tm2.Text = "New";
tm3.Text = "Open";
tm4.Text = "Save";
tm5.Text = "Close";
tm6.Text = "Edit";
tm7.Text = "Width line";
tm8.Text = "Background";
tm9.Text = "Color of the line";
tm10.Text = "Info";
tm11.Text = "Choice shape";
tm12.Text = "Ellipse";
tm13.Text = "Rectangle";
tm14.Text = "Arrow";
tm1.DropDownItems.Add(tm2);
tm1.DropDownItems.Add(tm3);
tm1.DropDownItems.Add(tm4);
tm1.DropDownItems.Add(tm5);
tm6.DropDownItems.Add(tm7);
tm6.DropDownItems.Add(tm8);
tm6.DropDownItems.Add(tm9);
tm11.DropDownItems.Add(tm12);
tm11.DropDownItems.Add(tm13);
tm11.DropDownItems.Add(tm14);
tm2.Image = Image.FromFile(Application.StartupPath + @"\" + "1.bmp");
tm3.Image = Image.FromFile(Application.StartupPath + @"\" + "2.bmp");
tm4.Image = Image.FromFile(Application.StartupPath + @"\" + "3.bmp");
tm5.Image = Image.FromFile(Application.StartupPath + @"\" + "5.bmp");
t1.Items.Add(tb1);
t1.Items.Add(tb2);
t1.Items.Add(tb3);
t1.Items.Add(ts1);
t1.Items.Add(tb4);
tb1.Image = Image.FromFile(Application.StartupPath + @"\" + "1.bmp");
tb2.Image = Image.FromFile(Application.StartupPath + @"\" + "2.bmp");
tb3.Image = Image.FromFile(Application.StartupPath + @"\" + "3.bmp");
tb4.Image = Image.FromFile(Application.StartupPath + @"\" + "4.bmp");
cd1.Color = Color.Aqua;
ss.Items.Add(tss1);
ss.Items.Add(tss2);
IsMdiContainer = true;
ShapeName = "Arrow";
}
void tb1_Click(object Sender, EventArgs e) //обработчик нажатия кнопки {
MDIChild F2 = new MDIChild(); //создание дочерней формы
F2.MdiParent = this;
F2.Show();
}
void tb2_Click(object Sender, EventArgs e)
{
MDIChild Active = ActiveMdiChild as MDIChild;//
if (Active == null)
{
tb1_Click(Sender, e);
Active = ActiveMdiChild as MDIChild;
}
Active.OpenList();
}
void tb3_Click(object Sender, EventArgs e)
{
MDIChild Active = ActiveMdiChild as MDIChild;
if (Active != null)
Active.SaveList();
}
void tm5_Click(object Sender, EventArgs e)
{
this.Close();
}
void tm7_Click(object Sender, EventArgs e)
{
WidthForm F3 = new WidthForm();
F3.Owner = this;
F3.ShowDialog();
}
void tm8_Click(object Sender, EventArgs e)
{
cd1.ShowDialog(this);
}
void tm9_Click(object Sender, EventArgs e)
{
cd2.ShowDialog(this);
}
void tm10_Click(object Sender, EventArgs e)
{
InfoForm F4 = new InfoForm();
F4.Owner = this;
F4.ShowDialog();
}
void tm12_Click(object Sender, EventArgs e)
{
ShapeName = (Sender as ToolStripMenuItem).Text;
}
public string XMouse
{
set
{
tss1.Text = "X = " + value;
}
}
public string YMouse
{
set
{
tss2.Text = "Y = " + value;
}
}
public Color getBackground
{
get
{
return cd1.Color;
}
}
public Color getPenColor
{
get
{
return cd2.Color;
}
}
public int WidthLine
{
set
{
VarWidthLine = value;
}
get
{
return VarWidthLine;
}
}
}
class Prg
{
static void Main()
{
MyForm f = new MyForm();
Application.Run(f);
}
}
class WidthForm : Form//Форма установки толщины
{
MyForm Form1;
HScrollBar hsb = new HScrollBar();
Label lb1 = new Label();
public WidthForm()
{
Text = "Width of the line";
FormClosed += new FormClosedEventHandler(WidthForm_FormClosed);
StartPosition = FormStartPosition.CenterParent;
hsb.Scroll += new ScrollEventHandler(hsb_Scroll);
Height = 100;
Width = 250;
MaximizeBox = false;
lb1.Top = 10;
lb1.Left = 115;
lb1.Text = "1";
lb1.Parent = this;
hsb.Top = 30;
hsb.Left = 20;
hsb.Width = 200;
hsb.Maximum = 20;
hsb.Minimum = 1;
hsb.LargeChange = 1;
hsb.Parent = this;
}
void WidthForm_FormClosed(Object sender, FormClosedEventArgs e)//Вернуть значение при закрытии
{
Form1 = this.Owner as MyForm;
Form1.WidthLine = Convert.ToInt32(lb1.Text);
}
void hsb_Scroll(object Sender, ScrollEventArgs e)
{
lb1.Text = Convert.ToString(e.NewValue);
}
}
class InfoForm : Form//информативное окно
{
Label lb1 = new Label();
Label lb2 = new Label();
public InfoForm()
{
Text = "Info about Lab5";
StartPosition = FormStartPosition.CenterParent;
Width = 250;
Height = 95;
MaximizeBox = false;
MinimizeBox = false;
lb1.Top = 15;
lb1.Left = 10;
lb1.Width = 200;
lb1.Height = 30;
lb1.Text = "The program is realization of laboratory work number 5";
lb1.Parent = this;
}
}
interface IShape //интерфейс фигуры
{
int x { get; set; }
int y { get; set; }
int width { get; set; }
Color background { get; set; }
Color PenColor { get; set; }
void Drow(Graphics g);
}
[Serializable()]
class myEllipse : IShape//класс Эллипс
{
public int x { get; set; }
public int y { get; set; }
public int width { get; set; }
public Color background { get; set; }
public Color PenColor { get; set; }
public void Drow(Graphics g)
{
g.FillEllipse(new SolidBrush(background), x, y, 60, 40);
g.DrawEllipse(new Pen(PenColor, width), x, y, 60, 40); }
}
[Serializable()]
class myRectangle : IShape//класс Прямоугольник
{
public int x { get; set; }
public int y { get; set; }
public int width { get; set; }
public Color background { get; set; }
public Color PenColor { get; set; }
public void Drow(Graphics g)
{
g.FillRectangle(new SolidBrush(background), x, y, 60, 40);
g.DrawRectangle(new Pen(PenColor, width), x, y, 60, 40);
}
}
[Serializable()]
class Arrow : IShape//класс Стрелка {
public int x { get; set; }
public int y { get; set; }
public int width { get; set; }
public Color background { get; set; }
public Color PenColor { get; set; }
public void Drow(Graphics g)
{
Point[] curvePoints =
{
new Point(x, y),
new Point(x + 40, y),
new Point(x + 40, y - 10),
new Point(x + 60, y + 10),
new Point(x + 40, y + 30),
new Point(x + 40, y + 20),
new Point(x, y + 20)
};
g.FillPolygon(new SolidBrush(background), curvePoints);
g.DrawPolygon(new Pen(PenColor, width), curvePoints);
}
}
static class ShapeFactory //Фабрика
{
public static IShape GetShape(string ShapeName)//создаёт новую фигуру
{
IShape result = null;
switch (ShapeName)
{
case "Ellipse": result = new myEllipse();
break;
case "Rectangle": result = new myRectangle();
break;
case "Arrow": result = new Arrow();
break;
}
return result;
}
}
[Serializable()]
abstract class Decorator : IShape//Декоратор
{
public int x { get; set; }
public int y { get; set; }
public int width { get; set; }
public Color background { get; set; }
public Color PenColor { get; set; }
protected IShape shape;
public Decorator(IShape s)
{
shape = s; }
public virtual void Drow(Graphics g)
{
shape.x = x;
shape.y = y;
shape.width = width;
shape.PenColor = PenColor;
shape.background = background;
shape.Drow(g);
}
}
[Serializable()]
class TextDecorator : Decorator//Реализация декоратора
{
string Text;
public TextDecorator(IShape s, string t)
: base(s)
{
Text = t;
}
public override void Drow(Graphics g)
{
base.Drow(g);
g.DrawString(Text, new Font("Arial", 8), Brushes.Black, new Point(shape.x + 5, shape.y + 5));
}
}
class MDIChild : Form//Дочерняя форма
{
SaveFileDialog sfd1 = new SaveFileDialog();
OpenFileDialog ofd1 = new OpenFileDialog();
string NameFile;
string ShapeName;
IShape Pict1;
MyForm Form1;
int x, y;
List<IShape> list = new List<IShape>();//список фигур
public MDIChild()
{
Text = "Child Form";
NameFile = Text;
MouseMove += new MouseEventHandler(MDIChild_MouseMove);
Click += new EventHandler(MDIChild_Click);
Paint += new PaintEventHandler(MDIChild_Paint);
Activated += new EventHandler(MDIChild_Activated);
Top = 150;
Left = 25;
Height = 150;
Width = 240;
sfd1.Filter = "dat files (*.dat)|*.dat|All files (*.*)|*.*";
sfd1.FilterIndex = 1;
sfd1.RestoreDirectory = true;
ofd1.Filter = "dat files (*.dat)|*.dat|All files (*.*)|*.*";
ofd1.FilterIndex = 1;
ofd1.RestoreDirectory = true;
}
void MDIChild_MouseMove(object Sender, MouseEventArgs e)
{
x = e.X;
y = e.Y;
Form1.XMouse = Convert.ToString(x);
Form1.YMouse = Convert.ToString(y);
}
void MDIChild_Click(object Sender, EventArgs e)
{
ShapeName = Form1.ShapeName;
Pict1 = new TextDecorator(ShapeFactory.GetShape(ShapeName),ShapeName);//вызов декоратора и фабрики
Pict1.x = x;
Pict1.y = y;
Pict1.background = Form1.getBackground;
Pict1.PenColor = Form1.getPenColor;
Pict1.width = Form1.WidthLine;
list.Add(Pict1);
Invalidate();
}
void MDIChild_Paint(object Sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
foreach (IShape i in list)
{
i.Drow(g);
}
Text = NameFile;
Form1 = MdiParent as MyForm;
if (Form1.ActiveMdiChild == this)
Form1.Text = Text;
}
void MDIChild_Activated(object Sender, EventArgs e)
{
Form1 = MdiParent as MyForm;
Form1.Text = Text;
}
public void SaveList()
{
Thread newThread = new Thread(new ThreadStart(ThreadSave));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
}
void ThreadSave()
{
if (sfd1.ShowDialog() == DialogResult.OK)
{
if (sfd1.FileName != "")
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream outputStream = File.OpenWrite(sfd1.FileName);
formatter.Serialize(outputStream, list);
outputStream.Close();
NameFile = Path.GetFileName(sfd1.FileName);
Invalidate();
}
}
}
public void OpenList()
{
Thread newThread = new Thread(new ThreadStart(ThreadOpen));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
}
void ThreadOpen()
{
if (ofd1.ShowDialog() == DialogResult.OK)
{
if (ofd1.FileName != "")
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream inputStream = File.OpenRead(ofd1.FileName);
list = (List<IShape>)formatter.Deserialize(inputStream);
inputStream.Close();
Invalidate();
NameFile = Path.GetFileName(ofd1.FileName);
}
}
}
}
}
Документ
Категория
Рефераты
Просмотров
13
Размер файла
215 Кб
Теги
лабораторная работа, reports, лаба, лабораторная
1/--страниц
Пожаловаться на содержимое документа