C# Windows 窗体代码不工作 - 将事件附加到按钮

标签 c# winforms

有人能解释一下为什么下面的代码不起作用吗?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Speaker
{    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("bravo you did it");
    }
}
}

我设计的对应这段代码的窗口是一个单一按钮的单一窗口。我打算做一个相当扩展的程序,但遇到问题,我决定从一个小样本开始,看看有什么问题,但我发现这个简单的代码都不起作用。有什么建议么?当我按下按钮 1 时,什么也没有发生。

最佳答案

确保将事件 Click 附加到您的按钮上。您可以通过转到设计器来完成,双击按钮,它将在代码中为您创建事件处理程序。您还可以在表单构造函数中附加事件处理程序,例如:

public Form1()
{
    InitializeComponent();
    button1.Click += button1_Click;
}

您可以转到设计器,右键单击 Button1,单击属性,转到事件,然后您可以附加事件处理程序:

enter image description here

关于C# Windows 窗体代码不工作 - 将事件附加到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20197632/

相关文章:

c# - 在 C# 中快速复制 GUI?

c# - 上下移动 ListViewItems

c# - 如何在 C# 中制作一个像 Android 的 ListView 一样具有自定义内容的 ListView?

c# - ASP.NET 标识 : Generate random password

c# - .NET 中是否可以进行被动日志记录?

c# - 如何在基本的 MVC5.1 网站中正确注册 AutoFac?

c# - 如何使用 GC.KeepAlive() 以及用于什么目的?

c# - 使用正则表达式验证模型

c# - 使用 PostSharp,无法让 Multicast 为 WinForm 控件单击处理程序工作

c# - WPF 是否可以在 Windows 锁定屏幕顶部显示dialog()?