1、绑定Popup控件
需要对IsOpen属性进行赋值true(展示)或false(隐藏)
考虑用到MouseHook来判断鼠标是否在Popup内点击进行控件关闭,Popup是不会自动关闭的
//事件名MouseHook_HookEvent
var handle = (PresentationSource.FromVisual(TrayContextMenu.Child) as HwndSource).Handle;
//检索指定窗口的边界矩形的尺寸。尺寸以相对于屏幕左上角的屏幕坐标给出。
WinApi.User32.GetWindowRect(handle, out Rectangle rect);
if (rect.Left <= pos.X && pos.X <= rect.Right && pos.Y >= rect.Top && pos.Y <= rect.Bottom)
{
//Popup内操作,不做处理
}
else
{
//关闭Popup
Popup.IsOpen=false;
}
2、绑定ContextMenu
默认鼠标点击在控件外进行关闭
NotifyIcon NotifyIcon;
private void InitNotifyIcon()
{
//注册菜单栏
System.Windows.Forms.ContextMenu Menu = new System.Windows.Forms.ContextMenu();
System.Windows.Forms.MenuItem CloseItem = new System.Windows.Forms.MenuItem();
CloseItem.Text = "Close";
CloseItem.Click += CloseItem_Click;
System.Windows.Forms.MenuItem HelpItem = new System.Windows.Forms.MenuItem();
HelpItem.Text = "Help";
Menu.MenuItems.Add(HelpItem);
Menu.MenuItems.Add(CloseItem);
NotifyIcon = new NotifyIcon();
NotifyIcon.Click += NotifyIcon_Click;
NotifyIcon.Text = "Test";
NotifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Environment.CurrentDirectory+ "\\studio.ico");
NotifyIcon.Visible = true;
//绑定菜单栏
NotifyIcon.ContextMenu = Menu;
}
/// <summary>
/// 退出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CloseItem_Click(object sender, EventArgs e)
{
NotifyIcon.Visible = false;
this.Close();
}
/// <summary>
/// 窗体最小化恢复
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void NotifyIcon_Click(object sender, EventArgs e)
{
Visibility = 0;
if (this.WindowState == WindowState.Minimized)
this.WindowState = WindowState.Normal;
ShowInTaskbar = true;
Activate();
}
/// <summary>
/// 最小化窗体
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click(object sender, RoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}