обработчики событий наследования формы c # запускаются дважды - PullRequest
0 голосов
/ 21 января 2010

Я наследую от корневой формы, в которой есть кнопка «Далее» и «Назад», затем использую эти кнопки в некоторых подчиненных формах и вызываю кнопки дважды, я считаю, что проблема должна быть изложена в MSDN здесь: http://msdn.microsoft.com/en-us/library/e33683a5(VS.71).aspx

как бы я применил совет, который они дают к C #, а не к VB?

Это вызывает много проблем, когда все мои кнопки вызываются дважды, спасибо.

Код:

Корневая форма

public partial class rootForm : Form
    {
        public rootForm()
        {
            InitializeComponent();
        }

        private void rootForm_Load(object sender, EventArgs e)
        {
            //used for all generic strings e.g. buttons
            this.Text = Resources.UIStrings.FormTitle.ToString();
            this.btnNext.Text = Resources.UIStrings.btnNext.ToString();
            this.btnBack.Text = Resources.UIStrings.btnBack.ToString();
        }

От дизайнера:

        // btnNext
        // 
        this.btnNext.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        resources.ApplyResources(this.btnNext, "btnNext");
        this.btnNext.Name = "btnNext";
        this.btnNext.UseVisualStyleBackColor = true;

Форма установки

от дизайнера

        // 
        // btnNext
        // 
        this.btnNext.Location = new System.Drawing.Point(373, 360);
        this.btnNext.Size = new System.Drawing.Size(99, 23);
        this.btnNext.TabIndex = 7;
        this.btnNext.Text = "Install";
        this.btnNext.Click += new System.EventHandler(this.installButton_Click);

Из формы:

    private void installButton_Click(object sender, EventArgs e)
    {
     doSomeStuff();
    }

Вызов стека из VS для ОБА раз, когда событие вызывается

Installer.exe!Installer.InstallerForm.installButton_Click(object sender = {Text = "Siguiente"}, System.EventArgs e = {X = 21 Y = 10 Button = Left}) Line 226    C#

    [External Code] 

Installer.exe!Installer.Program.Main() Line 21 + 0x1d bytes C#

[External Code] 

Edit2 отслеживание обратного стека с точкой останова дает:

myInstaller.exe!myInstaller.InstallerForm.installButton_Click
[Native to Managed Transition]
[Managed to Native Transition]
System.Windows.Forms.dll!System.Windows.Forms.Control.OnClick
System.Windows.Forms.dll!System.Windows.Forms.Button.OnClick
System.Windows.Forms.dll!System.Windows.Forms.Button.OnMouseUp
System.Windows.Forms.dll!System.Windows.Forms.Control.WmMouseUp
System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc
System.Windows.Forms.dll!System.Windows.Forms.ButtonBase.WndProc
System.Windows.Forms.dll!System.Windows.Forms.Button.WndProc
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc
System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback
[Native to Managed Transition]
[Managed to Native Transition]
System.Windows.Forms.dll!System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop
System.Windows.Forms.dll!System.Windows.Forms.Application.Run
myInstaller.exe!myInstaller.Program.Main
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context
mscorlib.dll!System.Threading.ExecutionContext.Run
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart
 ******************* Function: myInstaller.InstallerForm.installButton_Click(object, System.EventArgs), Thread: 0xE00 Main Thread

myInstaller.exe!myInstaller.InstallerForm.installButton_Click
[Native to Managed Transition]
[Managed to Native Transition]
System.Windows.Forms.dll!System.Windows.Forms.Control.OnClick
System.Windows.Forms.dll!System.Windows.Forms.Button.OnClick
System.Windows.Forms.dll!System.Windows.Forms.Button.OnMouseUp
System.Windows.Forms.dll!System.Windows.Forms.Control.WmMouseUp
System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc
System.Windows.Forms.dll!System.Windows.Forms.ButtonBase.WndProc
System.Windows.Forms.dll!System.Windows.Forms.Button.WndProc
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc
System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback
[Native to Managed Transition]
[Managed to Native Transition]
System.Windows.Forms.dll!System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop
System.Windows.Forms.dll!System.Windows.Forms.Application.Run
myInstaller.exe!myInstaller.Program.Main
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context
mscorlib.dll!System.Threading.ExecutionContext.Run
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart
 ******************* Function: myInstaller.InstallerForm.installButton_Click(object, System.EventArgs), Thread: 0xE00 Main Thread

Если я присоединяюсь к разделу конструктора, где добавлен обработчик, я получаю

myInstaller.exe!myInstaller.InstallerForm.InitializeComponent
myInstaller.exe!myInstaller.InstallerForm.InstallerForm
myInstaller.exe!myInstaller.WelcomeForm.btnNext_Click
System.Windows.Forms.dll!System.Windows.Forms.Control.OnClick
System.Windows.Forms.dll!System.Windows.Forms.Button.OnClick
System.Windows.Forms.dll!System.Windows.Forms.Button.OnMouseUp
System.Windows.Forms.dll!System.Windows.Forms.Control.WmMouseUp
System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc
System.Windows.Forms.dll!System.Windows.Forms.ButtonBase.WndProc
System.Windows.Forms.dll!System.Windows.Forms.Button.WndProc
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc
System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback
[Native to Managed Transition]
[Managed to Native Transition]
System.Windows.Forms.dll!System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop
System.Windows.Forms.dll!System.Windows.Forms.Application.Run
myInstaller.exe!myInstaller.Program.Main
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context
mscorlib.dll!System.Threading.ExecutionContext.Run
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart
 ******************* Function: myInstaller.InstallerForm.InitializeComponent(), Thread: 0xA34 Main Thread

myInstaller.exe!myInstaller.InstallerForm.InitializeComponent
myInstaller.exe!myInstaller.InstallerForm.performChecks
myInstaller.exe!myInstaller.InstallerForm.InstallerForm
myInstaller.exe!myInstaller.WelcomeForm.btnNext_Click
System.Windows.Forms.dll!System.Windows.Forms.Control.OnClick
System.Windows.Forms.dll!System.Windows.Forms.Button.OnClick
System.Windows.Forms.dll!System.Windows.Forms.Button.OnMouseUp
System.Windows.Forms.dll!System.Windows.Forms.Control.WmMouseUp
System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc
System.Windows.Forms.dll!System.Windows.Forms.ButtonBase.WndProc
System.Windows.Forms.dll!System.Windows.Forms.Button.WndProc
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnMessage
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc
System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback
[Native to Managed Transition]
[Managed to Native Transition]
System.Windows.Forms.dll!System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop
System.Windows.Forms.dll!System.Windows.Forms.Application.Run
myInstaller.exe!myInstaller.Program.Main
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context
mscorlib.dll!System.Threading.ExecutionContext.Run
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart
 ******************* Function: myInstaller.InstallerForm.InitializeComponent(), Thread: 0xA34 Main Thread

Но это не должно быть так, как будто форма создается дважды? но если я ставлю точку останова на создателя установщика, она вызывается только один раз.

Ответы [ 5 ]

6 голосов
/ 21 января 2010

Не могли бы вы добавить код, как вы наследуете и используете кнопки? В C # такой проблемы не должно быть, потому что нет ключевого слова Handles.

Однако вы можете добавить несколько обработчиков времени к событию нажатия кнопки, например:

parent
    myButton.Click += myClickAction

child
    sameButton.Click += sameClickAction

При наследовании не следует нажимать на унаследованные кнопки в конструкторе (это добавит новое, может быть, то же самое действие на унаследованную кнопку)

Добавьте точку взлома в дважды выполненном действии, при нажатии обратитесь к окну CallStack Visual Studio, чтобы увидеть, кто вызывает ваш метод дважды ...

EDIT

Не уверен, что произойдет, но попробуйте следующее:

Заменить:

this.btnNext.Click += new System.EventHandler(this.installButton_Click);

с

this.btnNext.Click -= new System.EventHandler(this.installButton_Click);
this.btnNext.Click -= new System.EventHandler(this.installButton_Click);
this.btnNext.Click -= new System.EventHandler(this.installButton_Click);
this.btnNext.Click += new System.EventHandler(this.installButton_Click);

EDIT2

Чтобы мгновенно проанализировать вызовы вашего метода, выполните следующие действия:

  1. Установите точку трассировки в методе installButton_Click: альтернативный текст http://lh4.ggpht.com/_1TPOP7DzY1E/S13KtR6tpYI/AAAAAAAAC9s/GpCZpXEukv4/s800/3setBreackpoint.png

  2. Отредактируйте свойства точки трассировки, чтобы отследить стек вызовов (или также используйте просто $ CALLER - только предыдущую функцию): альтернативный текст http://lh6.ggpht.com/_1TPOP7DzY1E/S13KtE98okI/AAAAAAAAC9o/gW5TfXouQDM/s800/2brackpoint.png

  3. В окне «Вывод» деактивируйте (щелкните правой кнопкой мыши) все сообщения, кроме «Вывод программы»;

  4. Анализ выходных данных во время выполнения:

альтернативный текст http://lh4.ggpht.com/_1TPOP7DzY1E/S13Ks9YHEHI/AAAAAAAAC9k/WgnO5cBtUxI/s800/1output.png

0 голосов
/ 14 февраля 2019

Во время добавления данных в таблицу базы данных, когда я нажимаю кнопку добавления, затем автоматически запускаюсь дважды и с помощью этого кода проблема была решена.

public void addEmployee(object sender, EventArgs e)
                {

    controlsAdd.addBtn.Click -= new EventHandler(controlsAdd.addEmpInfToTable);
    controlsAdd.upDateBtn.Click -= new EventHandler(controlsAdd.updateEmployee); 
    controlsAdd.deleteBtn.Click -= new EventHandler(controlsAdd.deleEmployee);

     splitContainer1.Panel2.Controls.Clear();
     controlsAdd.AddControls(splitContainer1);


                }

Справка: https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-add-to-or-remove-from-a-collection-of-controls-at-run-time

0 голосов
/ 06 ноября 2013

когда вы создали форму B как унаследованную от базовой формы A, все события, определенные в форме A, автоматически активируются в вашей унаследованной форме B.

Если в вашей форме B вы добавите событие, то будет вызвано как событие базовой формы A, так и событие вашей новой формы B - сначала событие базовой формы, а затем событие вашей формы B.

если вы хотите «переопределить», то есть отключить базовое событие формы A, вам следует: 1) изменить объявление события формы с закрытого на защищенное (чтобы ваша форма B могла его видеть) 2) открыть конструктор формы B и вычесть это событие с помощью - =

0 голосов
/ 16 июня 2012

Если вы еще не решили его, попробуйте удалить создание (+ =) события в унаследованной форме и разрешить только метод события (button_click). В приведенном ниже примере я создал кнопку, которая используется в унаследованной форме, и ее поведение там отличается, но нет события пожара из базы:

FormA : Form 
{
   ...
   protected System.Windows.Forms.Button buttonBase = new System.Windows.Forms.Button();
   this.buttonBase.Click += new System.EventHandler(this.buttonBase_Click);

   protected virtual void buttonBase_Click(object sender, EventArgs e)
   {
       MessageBox.Show("Hi from base", "Hello");
   }
}

FormB : FormA
{
   ...
   // comment or remove line below, othervise you'll see "Hi from inherited form" twice
   // this.buttonBase.Click += new System.EventHandler(this.buttonBase_Click);         

   protected override void buttonBase_Click(object sender, EventArgs e)
   {
       MessageBox.Show("Hi from inherited form", "Elo");
   }
}
0 голосов
/ 21 января 2010

C # добавляет обработчики событий к элементам управления таким образом.

this.btnMyButton.Click + = new System.EventHandler (this.btnMyButton_Click);

Просто посмотрите, есть ли у вас что-то похожее на приведенное выше утверждение для вашей кнопки в производной форме, если это так, удалите / прокомментируйте ее, так как она добавляет дополнительный обработчик событий для этой кнопки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...