Question

I'm having a WPF application which I can minimize to tray. When I normal-click it, the window shows again.

Now I'm wondering how to create a simple ContextMenu?

The ContextMenu has to get filled with x options which onclick will run a function. For now I just need an 'Exit'-item linked to an 'Exit_Click' method.

Something I've tried is:

ContextMenu menu = (ContextMenu)this.FindResource("NotifierContextMenu");
menu.IsOpen = true;

menu doesn't know of any IsOpen value.

Other examples like to use a lot of different things. One of them requires me to create a HostManager for some reason.

I just need a simple ContextMenu. How can I achieve this?

Was it helpful?

Solution

As @H.B. mentioned Hardcodet's NotifyIcon is pretty darn good for WPF Taskbar icons. Sucks you don't get that out of the box with WPF but you might as well use it and address your issue than wait for Microsoft to fix it(They really should just add that library into standards)

Now to solve your issue(Using above solution):

  • Download the solution
  • Build the library
  • Add it to your source control if you have one and add a reference to it(Hardcodet.Wpf.TaskbarNotification.dll) in your project

Now in your MainWindow.xaml you could just have something like:

<Window ...
        xmlns:tb="http://www.hardcodet.net/taskbar"
        ...>
  ...
  <Grid>
    <tb:TaskbarIcon>
      <tb:TaskbarIcon.ContextMenu>
        <ContextMenu>
          <MenuItem Click="Exit_Click"
                    Header="Exit" />
        </ContextMenu>
      </tb:TaskbarIcon.ContextMenu>
    </tb:TaskbarIcon>
    ...
  </Grid>
</Window>

and MainWindow.xaml.cs with the click handler like you needed:

private void Exit_Click(object sender, RoutedEventArgs e) {
  Application.Current.Shutdown();
}

I do recommend spending some time looking at the examples coming with the source code of the library to familiarize yourself with your available options. Trust me wpf has it way too easy when it comes to helper libraries. Try some of qt helper libraries and you'll know what "buried in there somewhere" literally means in opensource helpers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top