我需要调用addDownload()
主应用程序类MainWindow.xaml.cs
中的方法App.xaml.cs
关于应用程序的一些信息:
在我的
App.xaml.cs
我有代码只运行应用程序的一个实例。(不是我的代码。我找到了)using System; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Windows; using DownloadManager; namespace DownloadManager { public partial class App : Application { private static readonly Semaphore singleInstanceWatcher; private static readonly bool createdNew; static App() { // Ensure other instances of this application are not running. singleInstanceWatcher = new Semaphore( 0, // Initial count. 1, // Maximum count. Assembly.GetExecutingAssembly().GetName().Name, out createdNew); if (createdNew) { // This thread created the kernel object so no other instance // of this application must be running. } else { // This thread opened an existing kernel object with the same // string name; another instance of this app must be running now. // Gets a new System.Diagnostics.Process component and the // associates it with currently active process. Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { NativeMethods.SetForegroundWindow( process.MainWindowHandle); NativeMethods.ShowWindow(process.MainWindowHandle, WindowShowStyle.Restore); break; } } // Terminate this process and gives the underlying operating // system the specified exit code. Environment.Exit(-2); } } private static class NativeMethods { [DllImport("user32.dll")] internal static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] internal static extern bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); } /// <summary> /// Enumeration of the different ways of showing a window.</summary> internal enum WindowShowStyle : uint { Hide = 0, ShowNormal = 1, ShowMinimized = 2, ShowMaximized = 3, Maximize = 3, ShowNormalNoActivate = 4, Show = 5, Minimize = 6, ShowMinNoActivate = 7, ShowNoActivate = 8, Restore = 9, ShowDefault = 10, ForceMinimized = 11 } } }
addDownload()
无论应用程序是否已经运行,我每次都需要将命令行参数传递给方法。
到目前为止我已经尝试过:
首先,我删除了 App.xaml 中的 Startup 入口点,因此我可以在代码隐藏中对其进行管理
然后,如果应用程序没有运行,创建一个新的 MainWindow 实例,并显示它:
MainWindow MW = new MainWindow(); MW.Show();
获取命令行参数,并将其传递给
addDownload()
方法:string[] args = Environment.GetCommandLineArgs(); if(args.Length > 1) { MW.addDownload(args[1]); }
好的,这部分工作完美。
但正如我所说,如果应用程序已经在运行,我也需要传递命令行参数。获取命令行参数和以前一样,但是将它传递给addDownload()
当前 MainWindow 实例的方法,不是,我很难找到一种工作方式;
我试过:
try
{
var main = App.Current.MainWindow as MainWindow;
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
main.addDownload(args[1]);
}
}
catch(Exception ex)
{
MessageBox.Show(String.Format("{0}\n{1}", ex.GetType().ToString(), ex.Message));
}
但是我得到一个 NullReferenceException ..我认为main
声明..我不知道如何在 Visual Studio 中调试这种特殊情况。
有什么帮助吗?我做错了什么?