在任何情況下都將顯示上下文菜單,但只有在鼠標位於選定文本上且不在richTextBox區域中的任何位置時才應啓用該菜單。只有當鼠標位置位於richTextBox中的選定文本上時,我如何才能啓用contextmenu菜單?
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
for (int i = 0; i < contextMenu.MenuItems.Count; i++)
{
if (richTextBox1.SelectedText != "")
{
contextMenu.MenuItems[i].Enabled = true;
}
else
{
contextMenu.MenuItems[i].Enabled = false;
}
}
}
}
僅當選擇了文本時,才啓用菜單項。 現在我想添加另一個條件,如果鼠標位置在選定的文本上,則啓用true。
如果不啓用false。因此,如果選擇文本,則應該有兩個條件,如果鼠標位於所選文本的任何部分,則應該有兩個條件。還不確定如何使第二個條件。
更新
我現在嘗試:
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
int positionToSearch = richTextBox1.GetCharIndexFromPosition(e.Location);
bool isInSelectedText = positionToSearch >= richTextBox1.SelectionStart && positionToSearch < richTextBox1.SelectionStart + richTextBox1.SelectionLength;
for (int i = 0; i < contextMenu.MenuItems.Count; i++)
{
if (richTextBox1.SelectedText != "" &&
isInSelectedText == true)
{
contextMenu.MenuItems[i].Enabled = true;
}
else
{
contextMenu.MenuItems[i].Enabled = false;
}
}
}
}
但是,當我提出用鼠標右鍵單擊選中的文本就會使菜單但當時如果我在其他地方右鍵單擊RichTextBox的區域該菜單仍然處於啓用狀態,我希望僅在選定的文本上啓用該菜單。
如果沒有選中的文本,則啓用虛假菜單。
我在窗體加載事件添加上下文菜單一次:
private void Form1_Load(object sender, EventArgs e)
{
contextMenu = new System.Windows.Forms.ContextMenu();
MenuItem menuItem = new MenuItem("Cut");
menuItem.Click += new EventHandler(CutAction);
contextMenu.MenuItems.Add(menuItem);
menuItem = new MenuItem("Copy");
menuItem.Click += new EventHandler(CopyAction);
contextMenu.MenuItems.Add(menuItem);
menuItem = new MenuItem("Paste");
menuItem.Click += new EventHandler(PasteAction);
contextMenu.MenuItems.Add(menuItem);
richTextBox1.ContextMenu = contextMenu;
for (int i = 0; i < contextMenu.MenuItems.Count; i++)
{
contextMenu.MenuItems[i].Enabled = false;
}
}
你的意思是像懸停在選定的文本應該啓用菜單? –
@Charles可能是的。 –