You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinForm点击鼠标显示文本失败,请求排查代码问题

问题:WinForms中动态创建的TextBox不显示

你在Form的MouseClick事件中编写了以下代码,但创建的TextBox并未显示:

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    int x = e.X;
    int y = e.Y;
    TextBox TextWithNumber = new TextBox();
    TextWithNumber.Width = 100;
    TextWithNumber.Height = 100;
    TextWithNumber.Location = new Point(x, y);
    TextWithNumber.Text = "TEXT";
    TextWithNumber.BackColor = Color.Green;
    TextWithNumber.ForeColor = Color.Red;
}

问题原因

你成功实例化了TextBox对象并设置了各项属性,但没有将这个TextBox添加到窗体的控件集合中。WinForms只有当控件被加入到容器(比如当前Form)的Controls集合时,才会在界面上渲染并显示该控件。

解决方案

在方法末尾添加一行代码,将创建好的TextBox添加到窗体的控件集合中:

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    int x = e.X;
    int y = e.Y;
    TextBox TextWithNumber = new TextBox();
    TextWithNumber.Width = 100;
    TextWithNumber.Height = 100;
    TextWithNumber.Location = new Point(x, y);
    TextWithNumber.Text = "TEXT";
    TextWithNumber.BackColor = Color.Green;
    TextWithNumber.ForeColor = Color.Red;
    // 添加此行代码
    Controls.Add(TextWithNumber);
}

内容的提问来源于stack exchange,提问作者user21396294

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 17:47:04