c# - 控制台应用程序中的 Application.Current "null"

标签 c# .net wpf multithreading f#

我目前正在尝试使用 WPF 组件,该组件利用 WPF 应用程序中的 Application.Current,但是由于多种原因,我从不调用 Application.Run(也不是一个选项)。结果是 NullReferenceException。

我主要是想从一个控制台应用程序中显示同一个 WPF 窗口的多个实例。 欢迎任何建议(以及 C#/F# 中的代码示例)!

提前致谢

最佳答案

只是提供一个替代解决方案。 可以在不打开任何窗口的情况下保持应用程序运行。对我来说,这感觉不那么“hackish”。 :) http://msdn.microsoft.com/en-us/library/system.windows.application.shutdownmode.aspx

public class AppCode : Application
{
   // Entry point method
   [STAThread]
   public static void Main()
   {
      AppCode app = new AppCode();
      app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
      app.Run();
      ...
      app.Shutdown();
   }
}

编辑: 好的,这有点麻烦。 Application.Run会阻塞,所以需要在自己的线程中运行。 当它在自己的线程中运行时,主线程和 ui 线程之间的任何交互最好由 Application.Current.Dispatcher.Invoke 完成。这是一些工作代码,假设您有一个继承自 Application 的类。我正在使用 WPF 项目模板为您创建的修改后的 App.xaml/App.xaml.cs,以便免费很好地处理 ResourceDictionaries。

public class Program
{
  // Entry point method
  [STAThread]
  public static void Main()
  {
     var thread = new System.Threading.Thread(CreateApp);
     thread.SetApartmentState(System.Threading.ApartmentState.STA);
     thread.Start();

     // This is kinda shoddy, but the thread needs some time 
     // before we can invoke anything on the dispatcher
     System.Threading.Thread.Sleep(100);

     // In order to get input from the user, display a
     // dialog and return the result on the dispatcher
     var result = (int)Application.Current.Dispatcher.Invoke(new Func<int>(() =>
        {
           var win = new MainWindow();
           win.ShowDialog();
           return 10;
        }), null);

     // Show something to the user without waiting for a result
     Application.Current.Dispatcher.Invoke(new Action(() =>
     {
        var win = new MainWindow();
        win.ShowDialog();
     }), null);

     System.Console.WriteLine("result" + result);
     System.Console.ReadLine();

     // This doesn't really seem necessary 
     Application.Current.Dispatcher.InvokeShutdown();
  }

  private static void CreateApp()
  {
     App app = new App();
     app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
     app.Run();
  }
}

关于c# - 控制台应用程序中的 Application.Current "null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37917477/

相关文章:

c# - 确保纯文本文件中存在一行的最有效方法

c# - 从元组到 ICollection 的映射

.net - 仅仅使用接口(interface)来促进单元测试中的 stub 和模拟现在已经过时了吗?

wpf - 使用 WPF WriteableBitmap.BackBuffer 绘制线条

c# - 通过控制边距移动图像

c# - Kinect 1.8 colorframe 和 depthframe 不协调

c# - <nativehr>0x80070057</nativehr><nativestack></nativestack> 在 Sharepoint 列表中创建选择字段时

c# - 需要快速的.NET ftp客户端

c# - 我可以在 URL 引用地址检查中使用什么来了解请求来 self 的域中的何处?

c# - 以编程方式 Web 服务代理类的代理凭据