c#+Winform實現自定義的“復制、粘貼”右鍵快捷菜單,多個控件共享使用一個右鍵菜單。


程序中需要用到文本框或者RichTextBox進行文字輸入或顯示,對於一般使用者,可能連快捷鍵Ctrl+C復制,Ctrl+V粘貼都不會用,作為開發者就必須做一個右鍵菜單,以顯示“復制”,“粘貼”。

可以將一個上下文菜單(ContextMenuStrip,也叫右鍵菜單、快捷菜單)分配給幾個控件使用,方法是將這幾個控件的ContextMenuStrip屬性設置為需要顯示的菜單。

在菜單事件中,如何判斷是在哪個控件點擊的呢?答案是此上下文菜單的SourceControl屬性,以下是復制、粘貼的代碼:

        private void 復制ToolStripMenuItem_Click(object sender, EventArgs e)
{
string selectText = ((RichTextBox)menuSend.SourceControl).SelectedText;
if (selectText != "")
{
Clipboard.SetText(selectText);
}
}

private void 粘貼ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Clipboard.ContainsText())
{
RichTextBox txtBox = (RichTextBox)menuSend.SourceControl;
int index = txtBox.SelectionStart; //記錄下粘貼前的光標位置
string text = txtBox.Text;
//刪除選中的文本
text = text.Remove(txtBox.SelectionStart, txtBox.SelectionLength);
//在當前光標輸入點插入剪切板內容
text = text.Insert(txtBox.SelectionStart, Clipboard.GetText());
txtBox.Text = text;
//重設光標位置
txtBox.SelectionStart = index;
}
}

 為了使右鍵菜單更顯智能,沒有選中文本時“復制”先效;剪切板無內容時,“粘貼”無效,特在其Opened事件中增加以下代碼。

 private void menuSend_Opened(object sender, EventArgs e)
{
//沒有選擇文本時,復制菜單禁用
string selectText = ((RichTextBox)menuSend.SourceControl).SelectedText;
if (selectText != "")
復制ToolStripMenuItem.Enabled = true;
else
復制ToolStripMenuItem.Enabled = false;
//剪切板沒有文本內容時,粘貼菜單禁用
if (Clipboard.ContainsText())
{
粘貼ToolStripMenuItem.Enabled = true;
}
else
粘貼ToolStripMenuItem.Enabled = false;

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM