【发布时间】:2017-07-12 06:22:05
【问题描述】:
在任何情况下都会显示上下文菜单,但只有当鼠标在选定的文本上而不是在 RichTextBox 区域中的任何位置时才应启用菜单。
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 区域的其他位置单击右键,菜单仍将启用,我希望仅在所选文本上启用它.
如果根本没有选定的文本,则启用 false 菜单。
我在表单加载事件中添加了一次上下文菜单:
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;
}
}
【问题讨论】:
-
您的意思是像将鼠标悬停在所选文本上应该启用菜单?
-
@CharlesMay 是的。