.NET
基于 .NET 软件框架的 Microsoft 技术。
85 个问题
使用.NET8的WPF如何基于XAML和CSharp实现具有复杂用户界面的任务栏通知,并且响应事件。可以在不停驻系统托盘的情况下发送任务栏通知吗?
在.NET 8的WPF中,创建一个复杂的用户界面任务栏通知,并响应事件是可以实现的。你可以使用 System.Windows.Forms.NotifyIcon 和 WPF 的相互操作来实现这一目标。下面是一个示例,展示如何基于XAML和C#实现具有复杂用户界面的任务栏通知,并响应事件。
MainWindow.xaml:
<StackPanel>
<Button Content="Show Notification" HorizontalAlignment="Center" VerticalAlignment="Center" Click="ShowNotification_Click"/>
</StackPanel>
MainWindow.xaml.cs:
using System.Windows;
using Application = System.Windows.Application;
namespace notification
{
public partial class MainWindow : Window
{
private NotifyIcon notifyIcon;
public MainWindow()
{
InitializeComponent();
CreateNotifyIcon();
}
private void CreateNotifyIcon()
{
notifyIcon = new NotifyIcon
{
Icon = new System.Drawing.Icon("C:\\...\\d.ico"),
Visible = false,
BalloonTipTitle = "Taskbar Notification",
BalloonTipText = "This is a notification from your WPF application.",
BalloonTipIcon = ToolTipIcon.Info
};
notifyIcon.DoubleClick += NotifyIcon_DoubleClick;
notifyIcon.BalloonTipClicked += NotifyIcon_BalloonTipClicked;
notifyIcon.ContextMenuStrip = new ContextMenuStrip();
notifyIcon.ContextMenuStrip.Items.Add("Show Notification", null, ShowNotification);
notifyIcon.ContextMenuStrip.Items.Add("Exit", null, (s, e) => Application.Current.Shutdown());
}
private void NotifyIcon_DoubleClick(object sender, EventArgs e)
{
this.Show();
this.WindowState = WindowState.Normal;
}
private void NotifyIcon_BalloonTipClicked(object sender, EventArgs e)
{
ShowNotificationWindow();
}
private void ShowNotification_Click(object sender, RoutedEventArgs e)
{
notifyIcon.Visible = true;
notifyIcon.ShowBalloonTip(3000);
}
private void ShowNotification(object sender, EventArgs e)
{
ShowNotificationWindow();
}
private void ShowNotificationWindow()
{
Dispatcher.Invoke(() =>
{
var notificationWindow = new NotificationWindow();
notificationWindow.Topmost = true;
notificationWindow.Show();
});
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
notifyIcon.Dispose();
base.OnClosing(e);
}
}
}
NotificationWindow:
<Window x:Class="notification.NotificationWindow"
...
Title="Notification" Height="200" Width="300" WindowStyle="None" AllowsTransparency="True" Background="Transparent">
<Grid Background="White" Margin="10" >
<StackPanel>
<TextBlock Text="This is a notification!" FontSize="16" Margin="10"/>
<Button Content="OK" Width="75" Margin="10" Click="Button_Click"/>
</StackPanel>
</Grid>
</Window>
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Windows.MessageBox.Show("show");
this.Close();
}
如果答案是正确的,请点击“接受答案”并点赞。 如果您对此答案还有其他疑问,请点击“评论”。
注意:如果您想接收相关电子邮件,请按照我们的文档中的步骤启用电子邮件通知 此线程的通知。