winforms 我需要获取调用事件处理程序的按钮的名称

ttp71kqs  于 2023-03-31  发布在  其他
关注(0)|答案(2)|浏览(132)

我正在创建一个应用程序来加载文本文件到两个提示。我希望能够编辑富文本框,并保存回文本文件。

按钮是通过代码创建的,它们都被分配给一个事件处理程序,以打开与它们的名称对应的文本文件(Preset1.txt将来自按钮Preset1)。我想获取按钮的名称并将其放入保存按钮事件处理程序中。
按钮保存事件需要获取引用它的按钮的名称,并将其发送到保存按钮,以便它可以保存到所述按钮选择的文本文件。
下面是我的全部代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.Remoting.Channels;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskBand;

namespace Shirohana
{
    public partial class fmMain : Form
    {
        public fmMain()
        {
            InitializeComponent();
        }

        public async void WaitSomeTime(Form item)
        {
            await Task.Delay(3000);
            item.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Set up the prompt text box
            int xPrompt, yPrompt;

            rtbPrompt.Font = lblPrompt.Font;

            pnlPrompt.Width    = rtbPrompt.Width  + 10;
            pnlPrompt.Height   = rtbPrompt.Height + 10;

            xPrompt            = rtbPrompt.Location.X;
            yPrompt            = rtbPrompt.Location.Y;

            pnlPrompt.Location = new Point(xPrompt-5,yPrompt-5);
            lblPrompt.Location = new Point(xPrompt-5,yPrompt-lblPrompt.Height-5);

            int xNegative, yNegative;

            rtbNegative.Font   = lblPrompt.Font;

            pnlNegative.Width  = rtbNegative.Width  + 10;
            pnlNegative.Height = rtbNegative.Height + 10;

            xNegative          = rtbNegative.Location.X;
            yNegative          = rtbNegative.Location.Y;

            pnlNegative.Location = new Point(xNegative - 5, yNegative - 5);
            lblNegative.Location = new Point(xNegative - 5, yNegative - lblNegative.Height - 5);

            ///////////////////////////////////////////////////////////////////////
            ///
            CreateButtons();

        }
        public void MissingPresetError()
        {
            MessageBox.Show("Please make sure Preset text file exists and is placed in the ShirohanaPresets folder.", "Preset File Missing!");
        }

        public void CreateButtons()
        {
            string fpath   = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ShirohanaAi\ShirohanaPresets";
            int fCount     = Directory.GetFiles(fpath, "*", SearchOption.TopDirectoryOnly).Length-1; // REPLACE THE COUNT
            int FileNumber = 1;
            int fileCount = 20-1;
            for (int i = 0; i < fileCount; i++)
            {
                FileNumber++;
                Button newButton = new Button();
                this.Controls.Add(newButton);
                newButton.Text                      = "PST "+FileNumber;
                newButton.Size                      = new Size(105, 50);
                newButton.Font                      = Preset1.Font;
                newButton.FlatStyle                 = FlatStyle.Flat;
                newButton.FlatAppearance.BorderSize = 0;
                newButton.BackColor                 = ColorTranslator.FromHtml("206, 100, 0");
                newButton.ForeColor                 = ColorTranslator.FromHtml("251, 248, 248");
                newButton.Margin                    = new Padding(8, 8, 8, 8);
                newButton.Name                      = "Preset"+FileNumber;
                newButton.Click += new EventHandler(btnPreset_Click);
                newButton.Click += new EventHandler(btnGetID);

                pnlPresets.Controls.Add(newButton);

                // CLEAR TEXT FILE File.WriteAllText(path, String.Empty);

                string create_path = fpath + @"\Preset" + FileNumber + ".txt";
                if (!File.Exists(create_path))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(create_path))
                    {
                        sw.WriteLine("PROMPT HERE - PRESET "+FileNumber);
                        sw.WriteLine("NEGATIVE HERE");
                        // To save a new prompt just delete the file and rewrite it with the text from the textboxes
                    }
                }

            }
            
        }

        private void btnGetID(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
        }

        private void btnPreset_Click(object sender, EventArgs e)
        {
            //Create path for presets
            string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ShirohanaAi\ShirohanaPresets";
            // If directory does not exist, create it
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            Button btn = (Button)sender;

            string textFile = path + @"\"+ btn.Name + ".txt";

            if (File.Exists(textFile))
            {
                string textContent = File.ReadAllText(textFile);
                string[] line = File.ReadAllLines(textFile);

                rtbPrompt.Text = line[0];
                rtbNegative.Text = line[1];

            }
            else
            {
                MissingPresetError();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // How do I get the button name???
            string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ShirohanaAi\ShirohanaPresets";
            string textFile = path + @"\" + btn.Name + ".txt";
        }

        #region Copy Buttons
        private void btnCopyPrompt_Click(object sender, EventArgs e)
        {
            if (rtbPrompt.Text != "")
            { 
                System.Windows.Forms.Clipboard.SetText(rtbPrompt.Text);
                new ToolTip().Show("Copied Prompt Info!",this, rtbPrompt.Location.X + 100 , rtbPrompt.Location.Y, 1000);
            }
            else
            {
                new ToolTip().Show("Empty!", this, rtbPrompt.Location.X + 100, rtbPrompt.Location.Y, 1000);
            }
        }

        private void btnCopyNegative_Click(object sender, EventArgs e)
        {
            if (rtbNegative.Text != "")
            {
                System.Windows.Forms.Clipboard.SetText(rtbNegative.Text);
                new ToolTip().Show("Copied Negative Prompt Info!",this, rtbNegative.Location.X + 170, rtbNegative.Location.Y, 1000);
            }
            else
            {
                new ToolTip().Show("Empty!", this, rtbNegative.Location.X + 170, rtbNegative.Location.Y, 1000);
            }
        }
        #endregion

    }
}
dohp0rv5

dohp0rv51#

我不确定你实际上是在使用Winform还是WPF
但以下内容应该对两者都适用。

private void btnSave_Click(object sender, EventArgs e)
{
   Button button = sender as Button;
   var name_of_button = button.Name;
   // name_of_button is now a string of the name of the clicked button
}
wkftcu5l

wkftcu5l2#

您可以将上次单击按钮的名称存储在一个变量中,并在同一表单中的其他处理程序中使用它。
1.在fmMain类中创建一个新变量:

public partial class fmMain : Form
{
    private string? lastPresetButtonName;
    // all other code here
}

1.将新值保存到btnPreset_Click上的lastPresetButtonName

private void btnPreset_Click(object sender, EventArgs e)
{
    lastPresetButtonName = ((Button)sender).Name;
    // other code here
}

1.现在你可以从btnSave_Click中读取一个按钮名称:

private void btnSave_Click(object sender, EventArgs e)
{
    if (lastPresetButtonName != null)
    {
        string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ShirohanaAi\ShirohanaPresets";
        string textFile = path + @"\" + lastPresetButtonName + ".txt";
        // other code here
    }
}

相关问题