我有一个 Excel 插件(用 C# 和 ExcelDNA 编写),其表单用于允许用户将数据输入到从文本框继承的控件中。形式是模态的。进入控件会导致上下文菜单出现,其中包含基于用户输入的选项。
如果用户已输入数据并且上下文菜单可见,并且用户随后使另一个应用程序成为活动应用程序,则上下文菜单覆盖该应用程序。
是否有我可以在 Excel 应用程序之外使用的事件来确定 Excel 失去焦点?
我想出了一种让上下文菜单出现而不覆盖其他项目的方法。我的问题是在进入文本框期间上下文菜单始终可见,因为我在文本框 TextChanged 事件中将 AutoClose 属性设置为 false。现在,当我重新填充项目列表时,我在 TextChanged 事件中将 AutoClose 属性设置为 false。这是在输入第三个字符后输入到文本框中的任何击键完成的。
然后我创建了一个上下文菜单关闭事件,如下所示:
#region Instance Variables
ContextMenuStrip menuStrip = new System.Windows.Forms.ContextMenuStrip();
public event EventHandler EntryComplete;
public event EventHandler EntryNotComplete;
public event EventHandler EntryError;
#endregion
// Control Constructor
public AutoCompleteTextBox()
{
InitializeComponent();
menuStrip.PreviewKeyDown += menuStrip_PreviewKeyDown;
this.Leave += AutoCompleteTextBox_Leave;
// Use closing event so that we can determine when to close the menustrip.
menuStrip.Closing += new ToolStripDropDownClosingEventHandler(menuStrip_Closing);
}
void menuStrip_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
// only close the menu strip when an item is selected or the application loses focus
if (e.CloseReason != ToolStripDropDownCloseReason.ItemClicked &&
e.CloseReason != ToolStripDropDownCloseReason.AppFocusChange)
{
e.Cancel = true;
}
}
private void AutoCompleteTextBox_TextChanged(object sender, EventArgs e)
{
.
.
.
try
{
// get information on whether a ToolbarMenuItem has been selected
MenuItem info = new MenuItem();
MenuItemInfo selectedToolStripMenuInfo = info.SelectedItem(menuStrip);
menuStrip.AutoClose = true;
menuStrip.Visible = false;
menuStrip.Items.Clear();
if (selectedToolStripMenuInfo == null)
{
EntryNotComplete(sender, e);
}
if (base.Text.Length >= 3 && selectedToolStripMenuInfo == null)
{
.
.
.
menuStrip.AutoClose = false;
// foreach loop to add items into list
foreach (SearchType item in lst)
{
szMenuItem = ...;
ToolStripItem tsItem = new ToolStripMenuItem();
tsItem.Text = szMenuItem;
tsItem.Name = item.DealId;
tsItem.Click += tsItem_Click;
tsItem.Font = new Font("Courier New", 8.0F, FontStyle.Italic);
menuStrip.Items.Add(tsItem);
}
Point point = base.Location;
point.Offset(2, base.Height + 2);
point = base.GetPositionFromCharIndex(base.SelectionStart);
point.Offset(2, base.Font.Height + 2);
base.ContextMenuStrip = menuStrip;
base.ContextMenuStrip.Show(base.PointToScreen(point));
base.Focus();
menuStrip.AutoClose = true;
}
else if (base.Text.Length >= 3 && selectedToolStripMenuInfo != null)
{
EntryComplete(sender, e);
}
}
catch (Exception ex)
{
ErrorDescription = ex.Message;
menuStrip.AutoClose = true;
menuStrip.Visible = false;
EntryError(sender, e);
}
}