有时候想修改WPF程序的入口,在窗口启动前做一些操作。因为WPF的默认Main()入口处于App.g.i.cs中,修改这里的Main()是没有什么用的,它会自动恢复。
这时候解决方法如下,添加一个静态类,这里我命名为MainEntrance,它里面包含静态入口函数Main(),如下:
public static class MainEntrance
{
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main()
{
var args = System.Environment.GetCommandLineArgs();
var syncs = from arg in args
where arg.ToLower() == "sync" || arg.ToLower() == "/sync" || arg.ToLower() == "-sync"
select arg;
var atts = from arg in args
where arg.ToLower() == "att" || arg.ToLower() == "/att" || arg.ToLower() == "-att"
select arg;
if (atts.Count() == 0 && syncs.Count() == 0)
{
AttendanceAssistant.App app = new AttendanceAssistant.App();
app.InitializeComponent();
app.Run();
}
else if (atts.Count() > 0)
AAHelper.UpdateAttendanceLogToDatabase();
else if (syncs.Count() > 0)
AAHelper.SyncDataForDevices();
}
}
打开项目的属性页如下图,将启动对象改成刚才增加的静态类即可:
修改入口程序
补充:
增加一部分启动时使用不同的主窗口的代码样例:
public static class MainEntrance
{
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main()
{
InfoStore.App app = new InfoStore.App();
app.InitializeComponent();
#if DEBUG
app.StartupUri = new Uri("WindowMain.xaml", UriKind.Relative);
#else
app.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
#endif
app.Run();
}
}
达叔傻乐(darwin.zuo@163.com)
网友评论