如何解决我用C#编写的按钮类在运行时不会显示在Windows窗体中
刚开始学习Visual Studio,我正在尝试在Windows Forms中制作音板。 ButtonMaker();是用于为目录中的每个声音文件制作一个按钮的功能,因此我不必为每种声音制作70个不同的按钮,但是当我运行程序时,窗体窗口中没有任何显示。有人知道为什么吗?我试过在Main()和初始Form1类中调用该函数,但是在任何一个中都没有发生。表单类文件在这里:
UserDetailsService
这是SoundFiles类:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MySoundBoard
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
///Tried running it here
}
private void Form1_Load(object sender,EventArgs e)
{
///Tried running it here
}
private void ButtonMaker()
{
string[] files = Soundfiles.GetFile();
foreach (var item in files)
{
string btnName = item.ToUpper();
Button btNname = new Button();
btNname.Text = item;
int x = 40;
int y = 40;
btNname.Location = new Point(x,y);
x = x + 50;
if (x>900)
{
x = 40;
y = y + 30;
}
}
}
private void button1_Click(object sender,EventArgs e)
{
}
}
}
和主项目文件(尚未使用):
using System.IO;
using System;
using System.Text;
using System.Diagnostics;
using WMPLib;
namespace MySoundBoard
{
class Soundfiles {
WMPLib.WindowsMediaPlayer Player;
static public string[] GetFile() {
string txtPath = @"C:\Documents\path\to\sound effects";
string[] files =
Directory.GetFiles(txtPath,"*ProfileHandler.cs",SearchOption.TopDirectoryOnly);
return files;
}
public void PlayFile(String url)
{
Player = new WMPLib.WindowsMediaPlayer();
Player.URL = url;
Player.controls.play();
}
}
}
如前所述,我是这种语言的新手,任何帮助都将得到帮助!
解决方法
您创建了按钮,但从未将它们添加到表单中。只需添加
this.Controls.Add(btNname);
接下来的事情是,您的按钮将无法执行任何操作。您还需要添加一个事件处理程序。
btNname.Click += ...;
为了知道哪个按钮播放哪种声音,您需要找到一种方法来建立这种关联。骇人听闻的方法是
btNname.Tag = item;
,然后再评估Tag
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。