我正在開發的應用程序的一部分使用一些代碼根據從wmi搜索器中找到的可移動設備的數量動態創建文本框。從C#中通過ContextMenu訪問的動態創建的文本框中檢索值
由於我想要顯示更多關於這些設備的信息,並讓用戶能夠從程序本身中刪除設備,我改進了文本框,爲每個設備創建一個小的上下文菜單擴展選項。
每個選項都是使用事件處理程序創建的,因此當用戶單擊某個選項時,將執行相關操作。
現在,例如,要使用「刪除」選項,我需要知道哪個文本框已被用戶選中並獲取文本,以執行某些操作。
我該如何做到這一點?我如何知道用戶選擇了哪個文本框並獲取文本?
這是我到目前爲止有:
foreach (UsbDisk disk in disks)
{
++count;
TextBox[] usbTextBox = new TextBox[count];
for (int i = 0; i < 1; i++)
{
var txt = new TextBox();
var contextMenuUsbDev = new ContextMenuStrip();
var ExtView = contextMenuUsbDev.Items.Add("View Extended Properties");
var Remove = contextMenuUsbDev.Items.Add("Remove");
ExtView.Click += ExtView_Click;
Remove.Click += Remove_Click;
contextMenuUsbDev.RenderMode = ToolStripRenderMode.System;
contextMenuUsbDev.Size = new Size(211, 48);
contextMenuUsbDev.Location = new Point(390, 240 + (i * 45));
contextMenuUsbDev.Cursor = Cursors.Hand;
txt.Location = new Point(390, 240 + (i * 45));
txt.BackColor = Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20)))));
txt.ForeColor = Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
txt.Size = new Size(230,45);
txt.TabIndex = i;
txt.BorderStyle = BorderStyle.None;
txt.ReadOnly = true;
txt.Multiline = true;
txt.WordWrap = true;
txt.Font = new Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
txt.ContextMenuStrip = contextMenuUsbDev;
usbDevPanel.Controls.Add(txt);
txt.AppendText(CR + count + ") " + disk.ToString());
}
}
然後,下面,我有相應事件處理程序:
void Remove_Click(object sender, EventArgs e)
{ // Here I must perform the operations subject of this question, in order to proceed to removal operation}
void ExtView_Click(object sender, EventArgs e)
{
// Here I need the same code to know with which device properties populate the form below;
UsbDevicesProperties uDevP = new UsbDevicesProperties();
uDevP.Show();
}
任何人能幫助我。請?當我搜索了很多,但我似乎沒有找到任何可行的解決方案。
希望你的幫助。
謝謝。