gpt4 book ai didi

c# - 是否可以有多个控制button.Tag

转载 作者:太空狗 更新时间:2023-10-30 01:21:10 25 4
gpt4 key购买 nike

此应用会提示您打开一个文件夹。该应用程序然后查看文件夹中的所有文件并为每个 (.wav) 文件生成一个按钮。我的意图是在按下按钮时播放 (.wav) 文件。

我正在动态创建按钮。我使用 button.Tag 发送按钮编号,但我希望发送另一个包含 wav 文件完整路径的对象。我已经伪添加了它,但是我知道你不能像我一样添加两个 button.Tag。所以我的问题是如何实现它。

public partial class Form1 : Form
{
public SoundPlayer Sound1;
public static int btnCount = 0;

public Form1()
{
InitializeComponent();
SetFolderPath();
}

private void Form1_Load(object sender, EventArgs e)
{

}

public void addDynamicButton(string folder, string fileName)
{
btnCount++;
string soundfilepath = folder + "\\" + fileName + ".wav";

Button button = new Button();
button.Location = new Point(20, 30 * btnCount + 10);
button.Size = new Size(300, 23);

button.Text = fileName;
button.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
button.UseVisualStyleBackColor = true;

button.Click += new EventHandler(btnDynClickEvent);
button.Tag = btnCount;
button.Tag = soundfilepath;
this.Controls.Add(button);

}

void btnDynClickEvent(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{

switch ((int)button.Tag)
{
case 1:
Sound1 = new SoundPlayer((string)button.Tag);
Sound1.Play();
break;

}
}
}

public void SetFolderPath()
{

FolderBrowserDialog folder = new FolderBrowserDialog();

folder.Description = "Select the sound file Folder";

if (textBox1.Text.Length > 2)
{
folder.SelectedPath = textBox1.Text;
}

else
{
folder.SelectedPath = @"C:\";
}

if (folder.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folder.SelectedPath;

string[] files = Directory.GetFiles(folder.SelectedPath, "*.wav", SearchOption.AllDirectories);
int count = files.Length;

richTextBox1.Text = count.ToString() + " Files Found";

foreach (string file in files)
{
string fileName = Path.GetFileNameWithoutExtension(file);
addDynamicButton(folder.SelectedPath, fileName);
}
}
}


private void btnOpenFolder(object sender, EventArgs e)
{
SetFolderPath();
}


}

最佳答案

我建议在 Tag 属性中存储一个专门的对象:

class WaveDetailTag {

public FileInfo WaveFile {get; set;}
public int ButtonId {get; set;}

}

实现:

// ...
button.Tag = new WaveDetailTag() {
WaveFile = new FileInfo(soundfilepath),
ButtonId = btnCount
};
// ...

更新
switch-case 中使用:

    Button button = sender as Button;
if (button != null)
{
var waveDetail = (WaveDetailTag)button.Tag;
switch (waveDetail.ButtonId)
{
case 1:
Sound1 = new SoundPlayer(waveDetail.WaveFile.FullName);
Sound1.Play();
break;
}
}

关于c# - 是否可以有多个控制button.Tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16498991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com