WinForms任务栏图标 - 单击事件不触发 [英] WinForms Taskbar Icon - Click Event not firing
问题描述
我创建了一个使用NotifyIcon类的 非表单 c#程序。
I have created a non-form c# program that uses the NotifyIcon class.
文本 (单击以激活)当我悬停鼠标时显示。
所以我处理了一些事件。
The text "(Click to Activate)" shows up when I hover the mouse. So I am getting some events handled.
但是,点击事件不会触发,而且上下文菜单也不显示。
However, The "Click" event does not fire and the Context menu doesnt show up.
public class CTNotify
{
static NotifyIcon CTicon = new NotifyIcon();
static ContextMenu contextMenu = new ContextMenu();
static void Main()
{
//Add a notify Icon
CTicon.Icon = new Icon("CTicon.ico");
CTicon.Text = "(Click to Activate)";
CTicon.Visible = true;
CTicon.Click += new System.EventHandler(CTicon_Click);
//Create a context menu for the notify icon
contextMenu.MenuItems.Add("E&xit");
//Attach context menu to icon
CTicon.ContextMenu = contextMenu;
while (true) //Infinite Loop
{
Thread.Sleep(300); //wait
}
}
private static void CTicon_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Clicked!");
}
}
推荐答案
Take查看 Shell_NotifyIcon() API方法,实现NotifyIcon的方法。点击进入NOTIFYICONDATA结构。该结构的第二个成员是一个窗口句柄:
Take a look at the Shell_NotifyIcon() API method, the one that implements a NotifyIcon. Click through to the NOTIFYICONDATA structure. The second member of that structure is a window handle:
窗口的句柄,它接收与图标相关的
通知$通知区域中的b $ b
A handle to the window that receives notifications associated with an icon in the notification area
您没有窗口,因此无法接收通知。您必须将NotifyIcon放在表单上。并使用Application.Run()来获取通知并激活事件处理程序。
You don't have a window and can therefore not receive notifications. You must put the NotifyIcon on a Form. And use Application.Run() to get the notifications and activate the event handlers.
通过粘贴此代码来隐藏表单:
Keep your form hidden by pasting this code:
protected override void SetVisibleCore(bool value) {
if (!this.IsHandleCreated) {
this.CreateHandle();
value = false;
}
base.SetVisibleCore(value);
}
这篇关于WinForms任务栏图标 - 单击事件不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!