应用程序.当前“null"在控制台应用程序中
本文关键字:应用程序 控制台 当前 null quot | 更新日期: 2023-09-27 18:08:16
我目前正在尝试使用一个WPF组件,利用应用程序。目前从一个WPF应用程序,但由于几个原因,我从来没有调用应用程序。跑(这也不是一个选项)。结果是一个NullReferenceException。
我基本上试图从控制台应用程序中显示同一个WPF窗口的多个实例。欢迎提供任何建议(以及c#/f#代码示例)!
Thanks in advance
只是为了提供另一种解决方案。在不打开任何窗口的情况下保持应用程序运行是可能的。对我来说,这感觉不那么"粗俗"。:) 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();
}
}
编辑:这有点麻烦。应用程序。Run会阻塞,所以它需要在自己的线程中运行。当它在自己的线程中运行时,主线程和ui线程之间的任何交互最好由Application.Current.Dispatcher.Invoke完成。下面是一些工作代码,假设您有一个继承自Application的类。我正在使用修改后的App.xaml/App.xaml.cs,这是一个WPF项目模板为您创建的,以免费获得对资源词典的良好处理。
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();
}
}
以下是Application类的预期行为:
- 第一个打开的窗口是主窗口
- 列表中唯一的窗口成为主窗口(如果其他窗口)被移除)。
- 应用程序类被设计为在没有窗口时退出窗口列表。
点击此链接。
所以基本上你不能运行一个应用程序,没有任何窗口打开。开着一扇窗,但要藏起来。
如果我误解了你的问题,那么以下类似的例子可能会有所帮助:
-
管理托管WPF时的应用程序资源
-
在Visual Studio 2008中运行单元测试时