|
При нажатии на Сумма в примере ArbitraryMethod из Лекция 7, VS 2013 выдается ошибка: Необработанное исключение типа "System.InvalidOperationException" в System.Windows.Forms.dll Дополнительные сведения: Недопустимая операция в нескольких потоках: попытка доступа к элементу управления "lblResult" не из того потока, в котором он был создан. Затем: Необработанное исключение типа "System.InvalidOperationException" в mscorlib.dll Дополнительные сведения: Для каждой асинхронной операции метод EndInvoke может вызываться только один раз. |
Работа с элементами управления (продолжение)
Форма списка сообщений MessageList.cs
Значения свойства Name элементов управления этой формы приведены на рис. 3.31.
Полный листинг формы:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace MailApplication
{
/// <summary>
/// Summary description for MessageList.
/// </summary>
public class MessageList : System.Windows.Forms.Form
{
private Mail.Providers.Pop3 mail;
private UserIdentity identity;
private System.Windows.Forms.ListView lstViewMessages;
private System.Windows.Forms.ColumnHeader colFrom;
private System.Windows.Forms.ColumnHeader colSubject;
private System.Windows.Forms.ColumnHeader colDate;
private System.Windows.Forms.ImageList imageListIcons;
private System.Windows.Forms.ColumnHeader colIcon;
private System.Windows.Forms.Label lblMessagesCount;
private System.Windows.Forms.Panel pnlPages;
private System.ComponentModel.IContainer components;
public MessageList()
{
InitializeComponent();
identity = (UserIdentity)System.Threading.Thread.CurrentPrincipal.Identity;
// Создание объекта POP3.
if(identity.Pop3Port == -1)
mail = new Mail.Providers.Pop3(identity.Pop3);
else
mail = new Mail.Providers.Pop3(identity.Pop3, identity.Pop3Port);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support — do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MessageList));
this.lstViewMessages = new System.Windows.Forms.ListView();
this.colFrom = new System.Windows.Forms.ColumnHeader();
this.colSubject = new System.Windows.Forms.ColumnHeader();
this.colDate = new System.Windows.Forms.ColumnHeader();
this.imageListIcons = new System.Windows.Forms.ImageList(this.components);
this.colIcon = new System.Windows.Forms.ColumnHeader();
this.lblMessagesCount = new System.Windows.Forms.Label();
this.pnlPages = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// lstViewMessages
//
this.lstViewMessages.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lstViewMessages.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colIcon,
this.colFrom,
this.colSubject,
this.colDate});
this.lstViewMessages.Cursor = System.Windows.Forms.Cursors.Hand;
this.lstViewMessages.FullRowSelect = true;
this.lstViewMessages.GridLines = true;
this.lstViewMessages.Location = new System.Drawing.Point(16, 40);
this.lstViewMessages.MultiSelect = false;
this.lstViewMessages.Name = "lstViewMessages";
this.lstViewMessages.Size = new System.Drawing.Size(632, 352);
this.lstViewMessages.SmallImageList = this.imageListIcons;
this.lstViewMessages.TabIndex = 0;
this.lstViewMessages.View = System.Windows.Forms.View.Details;
this.lstViewMessages.Click += new System.EventHandler(this.lstViewMessages_Click);
//
// colFrom
//
this.colFrom.Text = "От";
this.colFrom.Width = 177;
//
// colSubject
//
this.colSubject.Text = "Тема";
this.colSubject.Width = 306;
//
// colDate
//
this.colDate.Text = "Дата";
this.colDate.Width = 106;
//
// imageListIcons
//
this.imageListIcons.ImageSize = new System.Drawing.Size(16, 16);
this.imageListIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListIcons.ImageStream")));
this.imageListIcons.TransparentColor = System.Drawing.Color.Transparent;
//
// colIcon
//
this.colIcon.Text = "#";
this.colIcon.Width = 39;
//
// lblMessagesCount
//
this.lblMessagesCount.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblMessagesCount.Location = new System.Drawing.Point(16, 8);
this.lblMessagesCount.Name = "lblMessagesCount";
this.lblMessagesCount.Size = new System.Drawing.Size(456, 23);
this.lblMessagesCount.TabIndex = 1;
this.lblMessagesCount.Text = "Писем в почтовом ящике: ";
this.lblMessagesCount.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// pnlPages
//
this.pnlPages.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pnlPages.Location = new System.Drawing.Point(16, 400);
this.pnlPages.Name = "pnlPages";
this.pnlPages.Size = new System.Drawing.Size(632, 32);
this.pnlPages.TabIndex = 2;
//
// MessageList
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(664, 438);
this.Controls.Add(this.pnlPages);
this.Controls.Add(this.lblMessagesCount);
this.Controls.Add(this.lstViewMessages);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MessageList";
this.Text = "Список сообщений";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.MessageList_Load);
this.ResumeLayout(false);
}
#endregion
private void MessageList_Load(object sender, System.EventArgs e)
{
try
{
// Вход в почтовый сервер.
mail.LogIn(identity.Name, identity.Password);
// Отображение количества сообщений.
lblMessagesCount.Text += mail.NumberOfMessages.ToString();
this.LoadCurrentPageMessages(1);
this.DrawPages(1);
}
catch(Exception ex)
{
MessageBox.Show("При выполнении подключения возникла ошибка: " + ex.Message);
}
}
/// <summary>
/// Прорисовывает листинг страниц.
/// </summary>
/// <param name="currentPageIndex">Номер текущей страницы.</param>
void DrawPages(uint currentPageIndex)
{
// Очищаем контейнер.
pnlPages.Controls.Clear();
uint messagesPerPage = 20;
uint pagesCount = (uint)(mail.NumberOfMessages / messagesPerPage);
// Отображаем номера существующих страниц.
for(uint i = 1; i <= pagesCount; i++)
{
LinkLabel page = new LinkLabel();
page.Text = i.ToString();
page.Tag = i;
page.Click += new EventHandler(page_Click);
if(i == currentPageIndex)
page.ForeColor = Color.Black;
page.Size = new Size(20, 20);
page.Location = new Point(30 * (int)i, 5);
pnlPages.Controls.Add(page);
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void page_Click(object sender, EventArgs e)
{
uint newPageIndex = Convert.ToUInt32(((LinkLabel)sender).Tag);
this.LoadCurrentPageMessages(newPageIndex);
this.DrawPages(newPageIndex);
}
/// <summary>
/// Отображает сообщения текущей страницы.
/// </summary>
/// <param name="currentPageIndex">Номер текущей страницы.</param>
void LoadCurrentPageMessages(uint currentPageIndex)
{
// Количество сообщений на странице.
uint messagesPerPage = 20;
// Индекс первого сообщения на странице.
uint startIndex = mail.NumberOfMessages — messagesPerPage * currentPageIndex;
// Индекс последнего сообщения на странице.
uint finishIndex = startIndex + 20;
// Загрузка заголовков сообщений.
for(uint currentMessageIndex = startIndex + 1;
currentMessageIndex <= finishIndex; currentMessageIndex++)
{
Mail.Message msg = null;
try
{
// Попытка загрузки заголовков сообщения.
msg = mail.GetMessageHeader(currentMessageIndex, 0);
}
catch(Exception ex)
{
// Отображение возникшей ошибки.
MessageBox.Show("При загрузке заголовков сообщения возникла ошибка. Номер сообщения: " +
currentMessageIndex + "; Текст ошибки: " + ex.Message);
}
// Если возникла ошибка, то пропускаем текущее сообщение.
if(msg == null)
continue;
// Отображение информации о сообщении.
ListViewItem item = new ListViewItem(
new string[]{currentMessageIndex.ToString(), msg.FromEmail, msg.Subject, msg.Date},
0);
item.Tag = currentMessageIndex;
lstViewMessages.Items.Add(item);
}
}
private void lstViewMessages_Click(object sender, System.EventArgs e)
{
try
{
// Получение номера выделенного сообщения.
uint messageIndex = Convert.ToUInt32(lstViewMessages.SelectedItems[0].Tag);
// Загрузка сообщения с сервера.
Mail.Message msg = mail.GetMessage(messageIndex);
// Отображение сообщения.
ViewMessage messageViewer = new ViewMessage(msg);
messageViewer.ShowDialog();
}
catch(Exception ex)
{
MessageBox.Show("Во время загрузки сообщения произошла следующая ошибка: " + ex.Message);
}
}
}
}
Листинг
3.23.
Форма ввода пароля PasswordPromt.cs
Для получения почты необходимо ввести пароль к своей учетной записи. Значения свойства Name элементов управления этой формы приведены на рис. 3.32.
Полный листинг формы:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace MailApplication
{
/// <summary>
/// Summary description for PasswordPromt.
/// </summary>
public class PasswordPromt : System.Windows.Forms.Form
{
private System.Windows.Forms.Label lblPassword;
private System.Windows.Forms.TextBox txbPassword;
private System.Windows.Forms.Button btnSubmit;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public PasswordPromt()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support — do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PasswordPromt));
this.lblPassword = new System.Windows.Forms.Label();
this.txbPassword = new System.Windows.Forms.TextBox();
this.btnSubmit = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lblPassword
//
this.lblPassword.Location = new System.Drawing.Point(16, 8);
this.lblPassword.Name = "lblPassword";
this.lblPassword.Size = new System.Drawing.Size(296, 23);
this.lblPassword.TabIndex = 0;
this.lblPassword.Text = "Введите пароль от почтового ящика";
this.lblPassword.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// txbPassword
//
this.txbPassword.Location = new System.Drawing.Point(16, 40);
this.txbPassword.Name = "txbPassword";
this.txbPassword.PasswordChar = '*';
this.txbPassword.Size = new System.Drawing.Size(296, 20);
this.txbPassword.TabIndex = 1;
this.txbPassword.Text = "";
//
// btnSubmit
//
this.btnSubmit.Location = new System.Drawing.Point(240, 72);
this.btnSubmit.Name = "btnSubmit";
this.btnSubmit.TabIndex = 2;
this.btnSubmit.Text = "ОК";
this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
//
// PasswordPromt
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(328, 110);
this.Controls.Add(this.btnSubmit);
this.Controls.Add(this.txbPassword);
this.Controls.Add(this.lblPassword);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PasswordPromt";
this.Text = "Запрос пароля";
this.ResumeLayout(false);
}
#endregion
private void btnSubmit_Click(object sender, System.EventArgs e)
{
if(txbPassword.Text == "")
{
MessageBox.Show("Пароль не может быть пустым");
}
else
{
this.DialogResult = DialogResult.OK;
((UserIdentity)System.Threading.Thread.CurrentPrincipal.Identity).Password = txbPassword.Text;
this.Close();
}
}
}
}
Листинг
3.24.
Форма выбора пользователя selectUser.cs
Форма выбора пользователя появляется при запуске программы, она также используется для смены пользователя. Значения свойства Name элементов управления этой формы приведены на рис. 3.33:
Полный листинг формы:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
namespace MailApplication
{
/// <summary>
/// Summary description for selectUser.
/// </summary>
public class selectUser : System.Windows.Forms.Form
{
public System.Windows.Forms.ListView lstViewUsers;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnSelect;
private System.Windows.Forms.Label lblUserSelect;
private System.Windows.Forms.ImageList imgLstUser;
private System.Windows.Forms.ColumnHeader colUserName;
private System.ComponentModel.IContainer components;
public selectUser()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support — do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(selectUser));
this.lstViewUsers = new System.Windows.Forms.ListView();
this.colUserName = new System.Windows.Forms.ColumnHeader();
this.imgLstUser = new System.Windows.Forms.ImageList(this.components);
this.btnCancel = new System.Windows.Forms.Button();
this.btnSelect = new System.Windows.Forms.Button();
this.lblUserSelect = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// lstViewUsers
//
this.lstViewUsers.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colUserName});
this.lstViewUsers.Cursor = System.Windows.Forms.Cursors.Hand;
this.lstViewUsers.GridLines = true;
this.lstViewUsers.Location = new System.Drawing.Point(8, 40);
this.lstViewUsers.MultiSelect = false;
this.lstViewUsers.Name = "lstViewUsers";
this.lstViewUsers.Size = new System.Drawing.Size(272, 176);
this.lstViewUsers.SmallImageList = this.imgLstUser;
this.lstViewUsers.TabIndex = 0;
this.lstViewUsers.View = System.Windows.Forms.View.Details;
//
// colUserName
//
this.colUserName.Text = "Имя пользователя";
this.colUserName.Width = 268;
//
// imgLstUser
//
this.imgLstUser.ImageSize = new System.Drawing.Size(16, 16);
this.imgLstUser.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgLstUser.ImageStream")));
this.imgLstUser.TransparentColor = System.Drawing.Color.Transparent;
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(200, 232);
this.btnCancel.Name = "btnCancel";
this.btnCancel.TabIndex = 1;
this.btnCancel.Text = "Отмена";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnSelect
//
this.btnSelect.Location = new System.Drawing.Point(128, 232);
this.btnSelect.Name = "btnSelect";
this.btnSelect.TabIndex = 2;
this.btnSelect.Text = "Выбор";
this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click);
//
// lblUserSelect
//
this.lblUserSelect.Location = new System.Drawing.Point(8, 8);
this.lblUserSelect.Name = "lblUserSelect";
this.lblUserSelect.Size = new System.Drawing.Size(272, 23);
this.lblUserSelect.TabIndex = 3;
this.lblUserSelect.Text = "Выберите пользователя из списка:";
this.lblUserSelect.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// selectUser
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.lblUserSelect);
this.Controls.Add(this.btnSelect);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.lstViewUsers);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "selectUser";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Выбор пользователя";
this.Load += new System.EventHandler(this.selectUser_Load);
this.ResumeLayout(false);
}
#endregion
private void selectUser_Load(object sender, System.EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(Environment.CurrentDirectory);
FileInfo[] users = dir.GetFiles("*.usr");
foreach(FileInfo user in users)
{
ListViewItem item = new ListViewItem(user.Name, 0);
lstViewUsers.Items.Add(item);
}
}
private void btnSelect_Click(object sender, System.EventArgs e)
{
if(lstViewUsers.SelectedItems.Count == 0)
MessageBox.Show("Выберите пользователя для начала работы", "Пользователь не выбран");
else
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
this.Close();
}
}
}
Листинг
3.25.
Форма отправки сообщений SendMessage.cs
На этой форме подготавливается сообщение к отправке. Значения свойства Name элементов управления приведены на рис. 3.34.
Полный листинг формы:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Web.Mail;
using System.Threading;
namespace MailApplication
{
/// <summary>
/// Summary description for SendMessage.
/// </summary>
public class SendMessage : System.Windows.Forms.Form
{
private MailMessage message;
private System.Windows.Forms.Label lblTo;
private System.Windows.Forms.TextBox txbTo;
private System.Windows.Forms.TextBox txbCopy;
private System.Windows.Forms.Label lblCopy;
private System.Windows.Forms.TextBox txbBlindCopy;
private System.Windows.Forms.Label lblBlindCopy;
private System.Windows.Forms.TextBox txbSubject;
private System.Windows.Forms.Label lblSubject;
private System.Windows.Forms.TextBox txbBody;
private System.Windows.Forms.Label lblBody;
private System.Windows.Forms.Button btnSend;
private System.Windows.Forms.Panel pblAttachments;
private System.Windows.Forms.Label lblAttachments;
private System.Windows.Forms.Button btnAddAttach;
private System.Windows.Forms.Button btnViewAttach;
private System.Windows.Forms.TextBox txbAttach;
private System.Windows.Forms.Label lblAttachNumber;
private System.Windows.Forms.OpenFileDialog oFDAttach;
private System.Windows.Forms.ContextMenu contextMenuDeleteAttach;
private System.Windows.Forms.MenuItem itemDeleteAttach;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public SendMessage()
{
InitializeComponent();
message = new MailMessage();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support — do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(SendMessage));
this.lblTo = new System.Windows.Forms.Label();
this.txbTo = new System.Windows.Forms.TextBox();
this.txbCopy = new System.Windows.Forms.TextBox();
this.lblCopy = new System.Windows.Forms.Label();
this.txbBlindCopy = new System.Windows.Forms.TextBox();
this.lblBlindCopy = new System.Windows.Forms.Label();
this.txbSubject = new System.Windows.Forms.TextBox();
this.lblSubject = new System.Windows.Forms.Label();
this.txbBody = new System.Windows.Forms.TextBox();
this.lblBody = new System.Windows.Forms.Label();
this.btnSend = new System.Windows.Forms.Button();
this.pblAttachments = new System.Windows.Forms.Panel();
this.lblAttachments = new System.Windows.Forms.Label();
this.btnAddAttach = new System.Windows.Forms.Button();
this.btnViewAttach = new System.Windows.Forms.Button();
this.txbAttach = new System.Windows.Forms.TextBox();
this.lblAttachNumber = new System.Windows.Forms.Label();
this.oFDAttach = new System.Windows.Forms.OpenFileDialog();
this.contextMenuDeleteAttach = new System.Windows.Forms.ContextMenu();
this.itemDeleteAttach = new System.Windows.Forms.MenuItem();
this.SuspendLayout();
//
// lblTo
//
this.lblTo.Location = new System.Drawing.Point(32, 16);
this.lblTo.Name = "lblTo";
this.lblTo.Size = new System.Drawing.Size(56, 23);
this.lblTo.TabIndex = 0;
this.lblTo.Text = "Кому:";
this.lblTo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// txbTo
//
this.txbTo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txbTo.Location = new System.Drawing.Point(112, 16);
this.txbTo.Name = "txbTo";
this.txbTo.Size = new System.Drawing.Size(560, 20);
this.txbTo.TabIndex = 1;
this.txbTo.Text = "";
//
// txbCopy
//
this.txbCopy.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txbCopy.Location = new System.Drawing.Point(112, 48);
this.txbCopy.Name = "txbCopy";
this.txbCopy.Size = new System.Drawing.Size(560, 20);
this.txbCopy.TabIndex = 3;
this.txbCopy.Text = "";
//
// lblCopy
//
this.lblCopy.Location = new System.Drawing.Point(32, 48);
this.lblCopy.Name = "lblCopy";
this.lblCopy.Size = new System.Drawing.Size(56, 23);
this.lblCopy.TabIndex = 2;
this.lblCopy.Text = "Копия:";
this.lblCopy.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// txbBlindCopy
//
this.txbBlindCopy.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txbBlindCopy.Location = new System.Drawing.Point(112, 80);
this.txbBlindCopy.Name = "txbBlindCopy";
this.txbBlindCopy.Size = new System.Drawing.Size(560, 20);
this.txbBlindCopy.TabIndex = 5;
this.txbBlindCopy.Text = "";
//
// lblBlindCopy
//
this.lblBlindCopy.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblBlindCopy.Location = new System.Drawing.Point(8, 80);
this.lblBlindCopy.Name = "lblBlindCopy";
this.lblBlindCopy.Size = new System.Drawing.Size(88, 23);
this.lblBlindCopy.TabIndex = 4;
this.lblBlindCopy.Text = "Скрытая копия:";
this.lblBlindCopy.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// txbSubject
//
this.txbSubject.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txbSubject.Location = new System.Drawing.Point(112, 112);
this.txbSubject.Name = "txbSubject";
this.txbSubject.Size = new System.Drawing.Size(560, 20);
this.txbSubject.TabIndex = 7;
this.txbSubject.Text = "";
//
// lblSubject
//
this.lblSubject.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblSubject.Location = new System.Drawing.Point(32, 112);
this.lblSubject.Name = "lblSubject";
this.lblSubject.Size = new System.Drawing.Size(72, 23);
this.lblSubject.TabIndex = 6;
this.lblSubject.Text = "Тема:";
this.lblSubject.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// txbBody
//
this.txbBody.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txbBody.Location = new System.Drawing.Point(16, 168);
this.txbBody.Multiline = true;
this.txbBody.Name = "txbBody";
this.txbBody.Size = new System.Drawing.Size(712, 192);
this.txbBody.TabIndex = 9;
this.txbBody.Text = "";
//
// lblBody
//
this.lblBody.Location = new System.Drawing.Point(16, 144);
this.lblBody.Name = "lblBody";
this.lblBody.TabIndex = 8;
this.lblBody.Text = "Текст сообщения:";
this.lblBody.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnSend
//
this.btnSend.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnSend.Location = new System.Drawing.Point(648, 440);
this.btnSend.Name = "btnSend";
this.btnSend.TabIndex = 10;
this.btnSend.Text = "Отправить";
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
//
// pblAttachments
//
this.pblAttachments.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pblAttachments.AutoScroll = true;
this.pblAttachments.Location = new System.Drawing.Point(16, 416);
this.pblAttachments.Name = "pblAttachments";
this.pblAttachments.Size = new System.Drawing.Size(608, 56);
this.pblAttachments.TabIndex = 12;
//
// lblAttachments
//
this.lblAttachments.Location = new System.Drawing.Point(16, 368);
this.lblAttachments.Name = "lblAttachments";
this.lblAttachments.Size = new System.Drawing.Size(64, 23);
this.lblAttachments.TabIndex = 13;
this.lblAttachments.Text = "Вложения:";
this.lblAttachments.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnAddAttach
//
this.btnAddAttach.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAddAttach.Location = new System.Drawing.Point(648, 368);
this.btnAddAttach.Name = "btnAddAttach";
this.btnAddAttach.TabIndex = 17;
this.btnAddAttach.Text = "Добавить";
this.btnAddAttach.Click += new System.EventHandler(this.btnAddAttach_Click);
//
// btnViewAttach
//
this.btnViewAttach.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnViewAttach.Location = new System.Drawing.Point(568, 368);
this.btnViewAttach.Name = "btnViewAttach";
this.btnViewAttach.TabIndex = 16;
this.btnViewAttach.Text = "Обзор";
this.btnViewAttach.Click += new System.EventHandler(this.btnViewAttach_Click);
//
// txbAttach
//
this.txbAttach.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txbAttach.Location = new System.Drawing.Point(176, 368);
this.txbAttach.Name = "txbAttach";
this.txbAttach.Size = new System.Drawing.Size(384, 20);
this.txbAttach.TabIndex = 15;
this.txbAttach.Text = "";
//
// lblAttachNumber
//
this.lblAttachNumber.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblAttachNumber.Location = new System.Drawing.Point(120, 368);
this.lblAttachNumber.Name = "lblAttachNumber";
this.lblAttachNumber.Size = new System.Drawing.Size(48, 23);
this.lblAttachNumber.TabIndex = 14;
this.lblAttachNumber.Text = "#";
this.lblAttachNumber.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// oFDAttach
//
this.oFDAttach.Title = "Выбор вложения";
//
// contextMenuDeleteAttach
//
this.contextMenuDeleteAttach.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.itemDeleteAttach});
//
// itemDeleteAttach
//
this.itemDeleteAttach.Index = 0;
this.itemDeleteAttach.Text = "Удалить";
this.itemDeleteAttach.Click += new System.EventHandler(this.itemDeleteAttach_Click);
//
// SendMessage
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(744, 478);
this.Controls.Add(this.btnAddAttach);
this.Controls.Add(this.btnViewAttach);
this.Controls.Add(this.txbAttach);
this.Controls.Add(this.txbBody);
this.Controls.Add(this.txbSubject);
this.Controls.Add(this.txbBlindCopy);
this.Controls.Add(this.txbCopy);
this.Controls.Add(this.txbTo);
this.Controls.Add(this.lblAttachNumber);
this.Controls.Add(this.lblAttachments);
this.Controls.Add(this.pblAttachments);
this.Controls.Add(this.btnSend);
this.Controls.Add(this.lblBody);
this.Controls.Add(this.lblSubject);
this.Controls.Add(this.lblBlindCopy);
this.Controls.Add(this.lblCopy);
this.Controls.Add(this.lblTo);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "SendMessage";
this.Text = "Отправка сообщения";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.ResumeLayout(false);
}
#endregion
private void btnViewAttach_Click(object sender, System.EventArgs e)
{
if(oFDAttach.ShowDialog() != DialogResult.OK)
return;
txbAttach.Text = oFDAttach.FileName;
}
private void btnAddAttach_Click(object sender, System.EventArgs e)
{
MailAttachment attach = new MailAttachment(oFDAttach.FileName);
message.Attachments.Add(attach);
txbAttach.Text = "";
oFDAttach.FileName = String.Empty;
this.AddAttachmentsToPanel();
}
private void AddAttachmentsToPanel()
{
pblAttachments.Controls.Clear();
for(int i = message.Attachments.Count -1; i >= 0; i--)
{
MailAttachment attach = (MailAttachment)message.Attachments[i];
Label lblNumber = new Label();
Label lblAttachName = new Label();
lblNumber.Text = String.Format("#{0}", i + 1);
lblAttachName.Text = attach.Filename;
lblAttachName.TextAlign = lblNumber.TextAlign = ContentAlignment.MiddleLeft;
lblAttachName.Anchor = lblNumber.Anchor = AnchorStyles.Top | AnchorStyles.Left;
lblNumber.Location = new Point(15, i*25);
lblAttachName.Location = new Point(50, i*25);
lblNumber.Size = new Size(20, 20);
lblAttachName.Size = new Size(500, 20);
lblNumber.ContextMenu = lblAttachName.ContextMenu = contextMenuDeleteAttach;
lblNumber.Tag = lblAttachName.Tag = i;
pblAttachments.Controls.Add(lblNumber);
pblAttachments.Controls.Add(lblAttachName);
}
}
private void itemDeleteAttach_Click(object sender, System.EventArgs e)
{
MenuItem item = (MenuItem)sender;
ContextMenu menu = (ContextMenu)item.Parent;
Label source = (Label)menu.SourceControl;
object o = source.Tag;
int i = Int32.Parse(o.ToString());
message.Attachments.RemoveAt(i);
this.AddAttachmentsToPanel();
}
private void btnSend_Click(object sender, System.EventArgs e)
{
message.BodyFormat = MailFormat.Text;
message.Body = txbBody.Text;
message.Cc = txbCopy.Text;
message.Bcc = txbBlindCopy.Text;
message.Subject = txbSubject.Text;
message.To = txbTo.Text;
message.From = ((UserIdentity)Thread.CurrentPrincipal.Identity).Mail;
Mail.MailSender mailSender = new Mail.MailSender(((UserIdentity)Thread.CurrentPrincipal.Identity).Smtp);
mailSender.Send(message, ((UserIdentity)Thread.CurrentPrincipal.Identity).Password);
MessageBox.Show("Ваше сообщение отправлено.");
this.Close();
}
}
}
Листинг
3.26.
Форма просмотра сообщений ViewMessage.cs
В эту форму загружается сообщение для чтения при его выборе из списка формы MessageList. Значения свойства Name элементов управления приведены на рис. 3.35.
Полный листинг формы:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace MailApplication
{
/// <summary>
/// Summary description for ViewMessage.
/// </summary>
public class ViewMessage : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label lblAttachments;
private System.Windows.Forms.Panel pblAttachments;
private System.Windows.Forms.Label lblBody;
private System.Windows.Forms.Label lblSubject;
private System.Windows.Forms.Label lblCopy;
private System.Windows.Forms.Label lblMessageBody;
private System.Windows.Forms.Label lblFrom;
private Mail.Message message;
public ViewMessage(Mail.Message msg)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.message = msg;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ViewMessage));
this.lblAttachments = new System.Windows.Forms.Label();
this.pblAttachments = new System.Windows.Forms.Panel();
this.lblBody = new System.Windows.Forms.Label();
this.lblSubject = new System.Windows.Forms.Label();
this.lblCopy = new System.Windows.Forms.Label();
this.lblFrom = new System.Windows.Forms.Label();
this.lblMessageBody = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// lblAttachments
//
this.lblAttachments.Location = new System.Drawing.Point(24, 280);
this.lblAttachments.Name = "lblAttachments";
this.lblAttachments.Size = new System.Drawing.Size(64, 23);
this.lblAttachments.TabIndex = 29;
this.lblAttachments.Text = "Вложения:";
this.lblAttachments.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// pblAttachments
//
this.pblAttachments.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pblAttachments.AutoScroll = true;
this.pblAttachments.Location = new System.Drawing.Point(128, 280);
this.pblAttachments.Name = "pblAttachments";
this.pblAttachments.Size = new System.Drawing.Size(544, 178);
this.pblAttachments.TabIndex = 28;
//
// lblBody
//
this.lblBody.Location = new System.Drawing.Point(24, 96);
this.lblBody.Name = "lblBody";
this.lblBody.TabIndex = 26;
this.lblBody.Text = "Текст сообщения:";
this.lblBody.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblSubject
//
this.lblSubject.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblSubject.AutoSize = true;
this.lblSubject.Location = new System.Drawing.Point(352, 16);
this.lblSubject.Name = "lblSubject";
this.lblSubject.Size = new System.Drawing.Size(35, 16);
this.lblSubject.TabIndex = 24;
this.lblSubject.Text = "Тема:";
this.lblSubject.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblCopy
//
this.lblCopy.AutoSize = true;
this.lblCopy.Location = new System.Drawing.Point(24, 56);
this.lblCopy.Name = "lblCopy";
this.lblCopy.Size = new System.Drawing.Size(40, 16);
this.lblCopy.TabIndex = 20;
this.lblCopy.Text = "Копия:";
this.lblCopy.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblFrom
//
this.lblFrom.AutoSize = true;
this.lblFrom.Location = new System.Drawing.Point(24, 24);
this.lblFrom.Name = "lblFrom";
this.lblFrom.Size = new System.Drawing.Size(47, 16);
this.lblFrom.TabIndex = 18;
this.lblFrom.Text = "От кого:";
this.lblFrom.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblMessageBody
//
this.lblMessageBody.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblMessageBody.Location = new System.Drawing.Point(136, 96);
this.lblMessageBody.Name = "lblMessageBody";
this.lblMessageBody.Size = new System.Drawing.Size(536, 176);
this.lblMessageBody.TabIndex = 30;
//
// ViewMessage
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(694, 476);
this.Controls.Add(this.lblMessageBody);
this.Controls.Add(this.lblAttachments);
this.Controls.Add(this.pblAttachments);
this.Controls.Add(this.lblBody);
this.Controls.Add(this.lblSubject);
this.Controls.Add(this.lblCopy);
this.Controls.Add(this.lblFrom);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "ViewMessage";
this.Text = "Просмотр сообщения";
this.Load += new System.EventHandler(this.ViewMessage_Load);
this.ResumeLayout(false);
}
#endregion
private void ViewMessage_Load(object sender, System.EventArgs e)
{
lblMessageBody.Text = this.message.Text;
lblCopy.Text += this.message.CC;
lblSubject.Text += this.message.Subject;
lblFrom.Text += this.message.FromEmail;
}
private void AddAttachmentsToPanel()
{
pblAttachments.Controls.Clear();
for(int i = message.Attachments.Length -1; i >= 0; i--)
{
//MailAttachment attach = (MailAttachment)message.Attachments[i];
Mail.AttachDescriptor attach = this.message.Attachments[i];
Label lblNumber = new Label();
Label lblAttachName = new Label();
lblNumber.Text = String.Format("#{0}", i + 1);
lblAttachName.Text = attach.Name;
lblAttachName.TextAlign = lblNumber.TextAlign = ContentAlignment.MiddleLeft;
lblAttachName.Anchor = lblNumber.Anchor = AnchorStyles.Top | AnchorStyles.Left;
lblNumber.Location = new Point(15, i*25);
lblAttachName.Location = new Point(50, i*25);
lblNumber.Size = new Size(20, 20);
lblAttachName.Size = new Size(500, 20);
//lblNumber.ContextMenu = lblAttachName.ContextMenu = contextMenuDeleteAttach;
lblNumber.Tag = lblAttachName.Tag = i;
pblAttachments.Controls.Add(lblNumber);
pblAttachments.Controls.Add(lblAttachName);
}
}
}
}
Листинг
3.27.




