Nexus.Client.Bootstrapper.RunMainForm C# (CSharp) Метод

RunMainForm() публичный Метод

Runs the applications
This method makes sure the environment is sane. If so, it creates the required services and launches the main form.
public RunMainForm ( string p_strArgs ) : bool
p_strArgs string The command line arguments passed to the application.
Результат bool
		public bool RunMainForm(string[] p_strArgs)
		{
			if (!SandboxCheck(m_eifEnvironmentInfo))
				return false;
			SetCompressorPath(m_eifEnvironmentInfo);

			string strRequestedGameMode = null;
			string[] strArgs = p_strArgs;
			Uri uriModToAdd = null;
			if ((p_strArgs.Length > 0) && !p_strArgs[0].StartsWith("-"))
			{
				if (Uri.TryCreate(p_strArgs[0], UriKind.Absolute, out uriModToAdd) && uriModToAdd.Scheme.Equals("nxm", StringComparison.OrdinalIgnoreCase))
					strRequestedGameMode = uriModToAdd.Host;
			}
			else
				for (Int32 i = 0; i < p_strArgs.Length; i++)
				{
					string strArg = p_strArgs[i];
					if (strArg.StartsWith("-"))
					{
						switch (strArg)
						{
							case "-game":
								strRequestedGameMode = p_strArgs[i + 1];
								Trace.Write("Game Specified On Command line: " + strRequestedGameMode + ") ");
								break;
						}
					}
				}

			bool booChangeDefaultGameMode = false;
			GameModeRegistry gmrSupportedGames = GetSupportedGameModes();
			do
			{
				NexusFontSetResolver nfrResolver = SetUpFonts();

				GameModeRegistry gmrInstalledGames = GetInstalledGameModes(gmrSupportedGames);
				if (gmrInstalledGames == null)
				{
					Trace.TraceInformation("No installed games.");
					MessageBox.Show(String.Format("No games were detected! {0} will now close.", m_eifEnvironmentInfo.Settings.ModManagerName), "No Games", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return false;
				}

				GameModeSelector gmsSelector = new GameModeSelector(gmrSupportedGames, gmrInstalledGames, m_eifEnvironmentInfo);
				IGameModeFactory gmfGameModeFactory = gmsSelector.SelectGameMode(strRequestedGameMode, booChangeDefaultGameMode);
				if (gmsSelector.RescanRequested)
				{
					m_eifEnvironmentInfo.Settings.InstalledGamesDetected = false;
					m_eifEnvironmentInfo.Settings.Save();
					booChangeDefaultGameMode = true;
					continue;
				}
				if (gmfGameModeFactory == null)
					return false;

				Trace.TraceInformation(String.Format("Game Mode Factory Selected: {0} ({1})", gmfGameModeFactory.GameModeDescriptor.Name, gmfGameModeFactory.GameModeDescriptor.ModeId));

				Mutex mtxGameModeMutex = null;
				bool booOwnsMutex = false;
				try
				{
					for (Int32 intAttemptCount = 0; intAttemptCount < 3; intAttemptCount++)
					{
						Trace.TraceInformation("Creating Game Mode mutex (Attempt: {0})", intAttemptCount);
						mtxGameModeMutex = new Mutex(true, String.Format("{0}-{1}-GameModeMutex", m_eifEnvironmentInfo.Settings.ModManagerName, gmfGameModeFactory.GameModeDescriptor.ModeId), out booOwnsMutex);

						//If the mutex is owned, you are the first instance of the mod manager for game mode, so break out of loop.
						if (booOwnsMutex)
							break;

						try
						{
							//If the mutex isn't owned, attempt to talk across the messager.
							using (IMessager msgMessager = MessagerClient.GetMessager(m_eifEnvironmentInfo, gmfGameModeFactory.GameModeDescriptor))
							{
								if (msgMessager != null)
								{
									//Messenger was created OK, send download request, or bring to front.
									if (uriModToAdd != null)
									{
										Trace.TraceInformation(String.Format("Messaging to add: {0}", uriModToAdd));
										msgMessager.AddMod(uriModToAdd.ToString());
									}
									else
									{
										Trace.TraceInformation(String.Format("Messaging to bring to front."));
										msgMessager.BringToFront();
									}
									return true;
								}
							}
							mtxGameModeMutex.Close();
							mtxGameModeMutex = null;
						}
						catch (InvalidOperationException)
						{
							StringBuilder stbPromptMessage = new StringBuilder();
							stbPromptMessage.AppendFormat("{0} was unable to start. It appears another instance of {0} is already running.", m_eifEnvironmentInfo.Settings.ModManagerName).AppendLine();
							stbPromptMessage.AppendFormat("If you were trying to download multiple files, wait for {0} to start before clicking on a new file download.", m_eifEnvironmentInfo.Settings.ModManagerName).AppendLine();
							MessageBox.Show(stbPromptMessage.ToString(), "Already running", MessageBoxButtons.OK, MessageBoxIcon.Information);
							return false;
						}
						//Messenger couldn't be created, so sleep for a few seconds to give time for opening
						// the running copy of the mod manager to start up/shut down
						Thread.Sleep(TimeSpan.FromSeconds(5.0d));
					}
					if (!booOwnsMutex)
					{
						HeaderlessTextWriterTraceListener htlListener = (HeaderlessTextWriterTraceListener)Trace.Listeners["DefaultListener"];
						htlListener.ChangeFilePath(Path.Combine(Path.GetDirectoryName(htlListener.FilePath), "Messager" + Path.GetFileName(htlListener.FilePath)));
						Trace.TraceInformation("THIS IS A MESSAGER TRACE LOG.");
						if (!htlListener.TraceIsForced)
							htlListener.SaveToFile();

						StringBuilder stbPromptMessage = new StringBuilder();
						stbPromptMessage.AppendFormat("{0} was unable to start. It appears another instance of {0} is already running.", m_eifEnvironmentInfo.Settings.ModManagerName).AppendLine();
						stbPromptMessage.AppendLine("A Trace Log file was created at:");
						stbPromptMessage.AppendLine(htlListener.FilePath);
						stbPromptMessage.AppendLine("Before reporting the issue, don't close this window and check for a fix here (you can close it afterwards):");
						stbPromptMessage.AppendLine("http://forums.nexusmods.com/index.php?/topic/721054-read-here-first-nexus-mod-manager-frequent-issues/");
						stbPromptMessage.AppendLine("If you can't find a solution, please make a bug report and attach the TraceLog file here:");
						stbPromptMessage.AppendLine("http://forums.nexusmods.com/index.php?/tracker/project-3-mod-manager-open-beta/");
						MessageBox.Show(stbPromptMessage.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
						return false;
					}

					//ApplicationInitializer ainInitializer = new ApplicationInitializer(m_eifEnvironmentInfo, nfrResolver);
					//ApplicationInitializationForm frmAppInitilizer = new ApplicationInitializationForm(ainInitializer);
					//ainInitializer.Initialize(gmfGameModeFactory, SynchronizationContext.Current);
					//frmAppInitilizer.ShowDialog();
					ApplicationInitializer ainInitializer = null;
					ApplicationInitializationForm frmAppInitilizer = null;
					while ((ainInitializer == null) || (ainInitializer.Status == TaskStatus.Retrying))
					{
						ainInitializer = new ApplicationInitializer(m_eifEnvironmentInfo, nfrResolver);
						frmAppInitilizer = new ApplicationInitializationForm(ainInitializer);
						ainInitializer.Initialize(gmfGameModeFactory, SynchronizationContext.Current);
						frmAppInitilizer.ShowDialog();
					}

					if (ainInitializer.Status != TaskStatus.Complete)
					{
						if (ainInitializer.Status == TaskStatus.Error)
							return false;
						booChangeDefaultGameMode = true;
						DisposeServices(ainInitializer.Services);
						continue;
					}

					IGameMode gmdGameMode = ainInitializer.GameMode;
					ServiceManager svmServices = ainInitializer.Services;

                    MainFormVM vmlMainForm = new MainFormVM(m_eifEnvironmentInfo, gmrInstalledGames, gmdGameMode, svmServices.ModRepository, svmServices.DownloadMonitor, svmServices.ActivateModsMonitor, svmServices.UpdateManager, svmServices.ModManager, svmServices.PluginManager);
					MainForm frmMain = new MainForm(vmlMainForm);

					using (IMessager msgMessager = MessagerServer.InitializeListener(m_eifEnvironmentInfo, gmdGameMode, svmServices.ModManager, frmMain))
					{
						if (uriModToAdd != null)
						{
							Trace.TraceInformation("Adding mod: " + uriModToAdd.ToString());
							msgMessager.AddMod(uriModToAdd.ToString());
							uriModToAdd = null;
						}

						Trace.TraceInformation("Running Application.");
						try
						{
							Application.Run(frmMain);
							svmServices.ModInstallLog.Backup();
							strRequestedGameMode = vmlMainForm.RequestedGameMode;
							booChangeDefaultGameMode = vmlMainForm.DefaultGameModeChangeRequested;
						}
						finally
						{
							DisposeServices(svmServices);
							gmdGameMode.Dispose();
						}
					}
				}
				finally
				{
					if (mtxGameModeMutex != null)
					{
						if (booOwnsMutex)
							mtxGameModeMutex.ReleaseMutex();
						mtxGameModeMutex.Close();
					}
					FileUtil.ForceDelete(m_eifEnvironmentInfo.TemporaryPath);

					//Clean up created font's.
					FontManager.Dispose();
				}
			} while (!String.IsNullOrEmpty(strRequestedGameMode) || booChangeDefaultGameMode);
			return true;
		}

Usage Example

Пример #1
0
        static void Main(string[] p_strArgs)
        {
            Mutex mtxAppRunningMutex = null;

            try
            {
                mtxAppRunningMutex = new Mutex(false, "Global\\6af12c54-643b-4752-87d0-8335503010de");

                bool booTrace = false;

                foreach (string strArg in p_strArgs)
                {
                    if (strArg.ToLower().Equals("/trace") || strArg.ToLower().Equals("-trace"))
                    {
                        booTrace = true;
                        break;
                    }
                }

                foreach (string strArg in p_strArgs)
                {
                    string[] strArgParts = strArg.Split('=');
                    if (strArgParts[0].ToLower().Equals("/u") || strArgParts[0].ToLower().Equals("-u"))
                    {
                        string           strGuid = strArgParts[1];
                        string           strPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
                        ProcessStartInfo psiInfo = new ProcessStartInfo(strPath + @"\msiexec.exe", "/x " + strGuid);
                        Process.Start(psiInfo);
                        return;
                    }
                }

#if DEBUG
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, true);
#else
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, false);
#endif

                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                UpgradeSettings(Properties.Settings.Default);
                EnvironmentInfo = new EnvironmentInfo(Properties.Settings.Default);

                if (!Directory.Exists(EnvironmentInfo.ApplicationPersonalDataFolderPath))
                {
                    Directory.CreateDirectory(EnvironmentInfo.ApplicationPersonalDataFolderPath);
                }

                EnableTracing(EnvironmentInfo, booTrace);

#if !DEBUG
                try
                {
#endif
                Bootstrapper btsInitializer = new Bootstrapper(EnvironmentInfo);
                try
                {
                    btsInitializer.RunMainForm(p_strArgs);
                }
                catch (MissingMethodException)
                {
                    if (MessageBox.Show("You're running an older version of the .Net Framework!" + Environment.NewLine + "Please download .Net Framework 4.6 from the Microsoft website or using Windows Update." +
                                        Environment.NewLine + Environment.NewLine + "Click YES if you want Nexus Mod Manager to automatically take you to the download page on your default browser." + Environment.NewLine +
                                        "Click NO if you want to close the program and download it later.", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=48137");
                    }

                    Application.Exit();
                }
#if !DEBUG
            }
            catch (Exception e)
            {
                HandleException(e);
            }
#endif

                Trace.TraceInformation(String.Format("Running Threads ({0})", TrackedThreadManager.Threads.Length));
                Trace.Indent();
                TrackedThread[] thdThreads = TrackedThreadManager.Threads;
                foreach (TrackedThread thdThread in thdThreads)
                {
                    Trace.TraceInformation(String.Format("{0} ({1}) ", thdThread.Thread.ManagedThreadId, thdThread.Thread.Name));
                    Trace.Indent();
                    if (thdThread.Thread.IsAlive)
                    {
                        Trace.TraceInformation("Aborted");
                        thdThread.Thread.Abort();
                    }
                    else
                    {
                        Trace.TraceInformation("Ended Cleanly");
                    }
                    Trace.Unindent();
                }
                Trace.Unindent();
            }
            catch (ConfigurationErrorsException e)
            {
                var userChoice = MessageBox.Show("It seems your Nexus Mod Manager application settings file has been corrupted, we can reset this file for you.\n\n" +
                                                 "Yes: Will reset your NMM related settings (scanned game locations, mod storage path, etc.) but will not remove your installed mods.\n\n" +
                                                 "No: Your settings will remain corrupted and NMM will crash when trying to start.", "Settings file corrupted",
                                                 MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                if (userChoice == DialogResult.Yes)
                {
                    var filename = e.Filename;

                    if (string.IsNullOrEmpty(filename) && e.InnerException.GetType() == typeof(ConfigurationErrorsException))
                    {
                        var inner = e.InnerException as ConfigurationErrorsException;
                        filename = inner.Filename;
                    }

                    try
                    {
                        File.Delete(filename);
                        MessageBox.Show("We've deleted your corrupted settings file, please restart Nexus Mod Manager.", "Settings reset", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    }
                    catch
                    {
                        MessageBox.Show("Something went wrong when trying to delete the settings file \"" + filename + "\".", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    }
                }
                else
                {
                    MessageBox.Show("Nothing has been done, Nexus Mod Manager will now shut down.", "Settings unchanged", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                }
            }
            finally
            {
                if (mtxAppRunningMutex != null)
                {
                    mtxAppRunningMutex.Close();
                }
            }
        }
All Usage Examples Of Nexus.Client.Bootstrapper::RunMainForm