Двойное срабатывание события Click
Здравствйте. Я пытаюсь реализовать паттерн проектирования MVP. Изначально были созданы три обычных кнопки button. После завершения проекта, решил изменить дизайн кнопок и ничего не придумал, как реализовать их через picturebox. И вот после изменения в проекте всех частей с button на picturebox событие стало срабатывать дважды. (Я просто изменил все места с указанием button на picturebox). Ниже приведу код. Первый "файл" это view, второй prosenter.
using System;
using System.Windows.Forms;
namespace HumanAsSystem
{
public interface IMainForms
{
event EventHandler ClickTask1;
event EventHandler ClickTask2;
event EventHandler ClickTask3;
}
public partial class MainForm : Form, IMainForms
{
#region Релизация IMainForms
public event EventHandler ClickTask1;
public event EventHandler ClickTask2;
public event EventHandler ClickTask3;
#endregion
public MainForm()
{
InitializeComponent();
Button1PictureBox.Click += new EventHandler(Button1PictureBox_Click);
Button2PictureBox.Click += new EventHandler(Button2PictureBox_Click);
Button3PictureBox.Click += new EventHandler(Button3PictureBox_Click);
}
#region События
private void Button1PictureBox_Click(object sender, EventArgs e)
{
if (ClickTask1 != null)
{
ClickTask1(this, EventArgs.Empty);
}
}
private void Button2PictureBox_Click(object sender, EventArgs e)
{
if (ClickTask2 != null)
{
ClickTask2(this, EventArgs.Empty);
}
}
private void Button3PictureBox_Click(object sender, EventArgs e)
{
if (ClickTask3 != null)
{
ClickTask3(this, EventArgs.Empty);
}
}
#endregion
private void MainForm_Load(object sender, EventArgs e)
{
}
Вот мой presenter
using System;
using HumanAsSystemTask1;
using HumanAsSystemTask2;
using HumanAsSystemTask3;
namespace HumanAsSystem
{
class MainPresenter
{
private readonly IMainForms _mainform;
private readonly MS.IMessageService _message_service;
public MainPresenter (IMainForms mainform, MS.IMessageService message_service)
{
_mainform = mainform;
_message_service = message_service;
_mainform.ClickTask1 += new EventHandler(_mainform_ClickTask1);
_mainform.ClickTask2 += new EventHandler(_mainform_ClickTask2);
_mainform.ClickTask3 += new EventHandler(_mainform_ClickTask3);
}
void _mainform_ClickTask1 (object sender, EventArgs e)
{
Task1Form form1 = new Task1Form();
form1.Show();
}
void _mainform_ClickTask2(object sender, EventArgs e)
{
Task2Form form2 = new Task2Form();
form2.Show();
}
void _mainform_ClickTask3(object sender, EventArgs e)
{
Task3Form form3 = new Task3Form();
form3.Show();
}
}
}
В С# не очень шарю, больше по с++. Поставили задачу сделать, и вот сталкиваюсь с разными проблемами и ничего не могу сообразить. Из-за различныз проблем и так выпилил часть функционала
MainFormDesigner
namespace HumanAsSystem
{
partial class MainForm
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором форм Windows
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.Button3PictureBox = new System.Windows.Forms.PictureBox();
this.Button2PictureBox = new System.Windows.Forms.PictureBox();
this.Button1PictureBox = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.Button3PictureBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Button2PictureBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Button1PictureBox)).BeginInit();
this.SuspendLayout();
//
// Button3PictureBox
//
this.Button3PictureBox.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.Button3PictureBox.Image = global::HumanAsSystem.Properties.Resources.Button3Up;
this.Button3PictureBox.Location = new System.Drawing.Point(12, 168);
this.Button3PictureBox.Name = "Button3PictureBox";
this.Button3PictureBox.Size = new System.Drawing.Size(200, 60);
this.Button3PictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.Button3PictureBox.TabIndex = 5;
this.Button3PictureBox.TabStop = false;
this.Button3PictureBox.Click += new System.EventHandler(this.Button3PictureBox_Click);
this.Button3PictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Button3PictureBox_MouseDown);
this.Button3PictureBox.MouseEnter += new System.EventHandler(this.Button3PictureBox_MouseEnter);
this.Button3PictureBox.MouseLeave += new System.EventHandler(this.Button3PictureBox_MouseLeave);
this.Button3PictureBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Button3PictureBox_MouseUp);
//
// Button2PictureBox
//
this.Button2PictureBox.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.Button2PictureBox.Image = global::HumanAsSystem.Properties.Resources.Button2Up;
this.Button2PictureBox.Location = new System.Drawing.Point(12, 102);
this.Button2PictureBox.Name = "Button2PictureBox";
this.Button2PictureBox.Size = new System.Drawing.Size(200, 60);
this.Button2PictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.Button2PictureBox.TabIndex = 4;
this.Button2PictureBox.TabStop = false;
this.Button2PictureBox.Click += new System.EventHandler(this.Button2PictureBox_Click);
this.Button2PictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Button2PictureBox_MouseDown);
this.Button2PictureBox.MouseEnter += new System.EventHandler(this.Button2PictureBox_MouseEnter);
this.Button2PictureBox.MouseLeave += new System.EventHandler(this.Button2PictureBox_MouseLeave);
this.Button2PictureBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Button2PictureBox_MouseUp);
//
// Button1PictureBox
//
this.Button1PictureBox.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.Button1PictureBox.Image = global::HumanAsSystem.Properties.Resources.Button1Up;
this.Button1PictureBox.Location = new System.Drawing.Point(12, 36);
this.Button1PictureBox.Name = "Button1PictureBox";
this.Button1PictureBox.Size = new System.Drawing.Size(200, 60);
this.Button1PictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.Button1PictureBox.TabIndex = 3;
this.Button1PictureBox.TabStop = false;
this.Button1PictureBox.Click += new System.EventHandler(this.Button1PictureBox_Click);
this.Button1PictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Button1PictureBox_MouseDown);
this.Button1PictureBox.MouseEnter += new System.EventHandler(this.Button1PictureBox_MouseEnter);
this.Button1PictureBox.MouseLeave += new System.EventHandler(this.Button1PictureBox_MouseLeave);
this.Button1PictureBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Button1PictureBox_MouseUp);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(213)))), ((int)(((byte)(225)))));
this.ClientSize = new System.Drawing.Size(502, 270);
this.Controls.Add(this.Button3PictureBox);
this.Controls.Add(this.Button2PictureBox);
this.Controls.Add(this.Button1PictureBox);
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "MainForm";
this.Text = "MainForm";
this.Load += new System.EventHandler(this.MainForm_Load);
((System.ComponentModel.ISupportInitialize)(this.Button3PictureBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Button2PictureBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Button1PictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox Button1PictureBox;
private System.Windows.Forms.PictureBox Button2PictureBox;
private System.Windows.Forms.PictureBox Button3PictureBox;
}
}
Ответы (1 шт):
У вас происходит дважды подписывание на события Click.
В конструкторе:
public MainForm()
{
InitializeComponent();
Button1PictureBox.Click += new EventHandler(Button1PictureBox_Click);
Button2PictureBox.Click += new EventHandler(Button2PictureBox_Click);
Button3PictureBox.Click += new EventHandler(Button3PictureBox_Click);
}
И в InitializeComponent() (задается в дизайнере формы):
this.Button3PictureBox.Click += new System.EventHandler(this.Button3PictureBox_Click);
this.Button2PictureBox.Click += new System.EventHandler(this.Button2PictureBox_Click);
this.Button1PictureBox.Click += new System.EventHandler(this.Button1PictureBox_Click);
Сколько раз подписались - столько раз и сработает.
Либо уберите в дизайнере подписывание на события, либо в конструкторе формы.