询问者
关于wpf main 函数

问题
-
默认情况下main 函数将自动创建在 app.g.cs中(这里面还包括了其他自动产生的代码),今天我想实现wpf单例应用程序,这又要求自己去写main 函数(我覆盖onrestartup发现没用),一般我们对于app启动只要:
/// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public static void Main() { skynote.App app = new skynote.App(); app.Run(); }
就可以了,但是这样产生的问题是,好像没有加载app.xaml,所以那里定义的resources都没有办法得到。我看到app.g.cs里是有#line hidden System.Uri resourceLocater = new System.Uri("/skynote;component/app.xaml", System.UriKind.Relative); #line 1 "..\..\App.xaml" System.Windows.Application.LoadComponent(this, resourceLocater);
这样来加载app.xaml,所以我想干脆把app.g.cs自动生成的其他代码也复制到我的app.xaml.cs中去吧,杯具的是,运行时又产生"找不到资源app.xaml",我已经把app.xaml设置为embeded resource了,难道自己写的这个加载就有问题吗?
全部回复
-
首先 引用Microsoft.VisualBasic
然后新建一个类 single
public class single:Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
App a;
public single()
{
this.IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
{
a = new App();
a.InitializeComponent();
a.Run();
return false;
}
protected override void OnStartupNextInstance(Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
a.activate();
}
}
app.cs
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Window1 w = new Window1();
w.Show();
}
public void activate()
{
MainWindow.Activate();
}
private void Application_SessionEnding(object sender, SessionEndingCancelEventArgs e)
{
}
private void Application_Startup(object sender, StartupEventArgs e)
{
}
private void Application_Exit(object sender, ExitEventArgs e)
{
}
}
app.g.cs
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main(string [] a ) {
single s = new single();
s.Run(a);
} -
-
如果您还在关心这个问题的话,您可以试试这个:
1 将App.xaml的生成操作改为“Page”
2 从App.g.cs中将Main的部分复制出来,粘贴到App.cs中
3 清理项目文件并重新编译生成
值得注意的是:
更改了生成操作以后App.g.cs中自动产生的InitializeComponent方法也会有些改变,但在我的简单测试中这种改变没有导致什么异常产生。
生成操作改为“Resource”也会有类似的效果。
Most questions i'm interested in might have two or more possible answers i know or i don't know. So please read question carefully before you try to answer, and explan your question detailedly before asking for help. 很多看起来简单的问题都存在多种可能性,如果您不能详细的解释,别人就不能正确判断出您所遭遇的实际状况,因而不能给出最适合的解决办法。在您没有给出详细信息的情况下,施助者只有张贴大量有可能有关的解决办法。而您可能没有耐心阅读所有这些东西,在这种情况下您就客观地形成了对施助者的伤害——除非“施助者”并没有用心去尝试帮助您。 同样地,当您尝试解答一个看起来“好像遇到过”的问题的时候,您也需要详细地阅读和理解这个问题。如果您不了解问题的细节,您可能会给出不相关的或者无助于解决当前问题的解答。