简体   繁体   中英

WPF WindowLess MessageBox

I'm attempting to convert a very small C# console application to WPF application. It takes in some parameters, does some work, and may bring up a MessageBox.

I'm moving it from a console app to WPF because it should run invisible, unless it has an error message.

The hitch, so far, has been getting it to show the MessageBox. The following is the really short version, that compiles, runs... but does not show the MessageBox.

namespace MyApp{
  public class EntryPoint {
    [STAThread]
    public static void Main(string[] args) {
        App app = new App();
        app.Run();
        MessageBox.Show("test", "test", MessageBoxButton.YesNo, MessageBoxImage.Question);
    }
  }
}

Anyone know how to get that pesky MessageBox to show, without having a main program window?

Your best bet may be to try and run the code in the application's Startup event. Keep in mind that WPF wasn't really designed to be used this way, so there may be some odd quirks.

Start by opening "App.xaml` in the solution explorer. The root of the XAML should look something like this:

<Application x:Class="Configurator.Application.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:FoodSafetyConfigurator"
             xmlns:s="clr-namespace:Configurator.Application.Properties"
             StartupUri="MainForm.xaml">

Remove the StartupUri="MainForm.xaml" attribute, and replace it with Startup="App_OnStartup" . That will stop WPF from displaying a window by default, and hook the startup event to a method in "App.xaml.cs" called App_Starup .

Now expand "App.xaml" in solution explorer, and open "App.xaml.cs"; this is the code behind file for "App.xaml". Add a method called App_OnStartup , which will be the target of the event we attached earlier. It should look something like this:

private void App_OnStartup(object sender, StartupEventArgs e)
{
    //Your code goes here.
}

Add any code you want to run in here. Any message boxes you display with MessageBox.Show() should display correctly, but I haven't actually tested it.

I ended up going with a standard Windows Forms application, and just removed the form. Figuring out how to make WPF do this was time consuming, frustrating and ultimately a failure. Forms may not be the new hotness, but it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM