2
此问题是关于WPF应用程序。 我想用我的自定义应用程序打开一些关联的文件。 我找到了打开关联文件的方法。 但仍然,我不知道如何处理重复的应用程序。例如, 如果点击“a.txt2”,我的应用程序将打开它。 我点击'a2.txt2',它也打开了我的应用程序的另一个过程。打开相关文件,如WPF中的'记事本++选项卡功能'
我想仅在第一个应用程序中获得第二次点击信息,而不是在单击关联文件时执行我的应用程序。 它与'记事本++'打开文件到选项卡功能类似。
这是我的代码。
1 MainWindow.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainContainer_Loaded);
}
void MainContainer_Loaded(object sender, RoutedEventArgs e)
{
string fn = "x";
if (Application.Current.Properties["ArbitraryArgName"] != null)
{
fn = Application.Current.Properties["ArbitraryArgName"].ToString();
}
this.Title = fn;
}
}
2的App.xaml
<Application x:Class="sample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Application.Resources>
</Application.Resources>
<!--
StartupUri="MainWindow.xaml"
Startup="App_Startup"--></Application>
3 app.cs
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
// Check if this was launched by double-clicking a doc. If so, use that as the
// startup file name.
string fname = "No filename given";
if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData != null
&& AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData.Length > 0)
{
try
{
fname = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
// It comes in as a URI; this helps to convert it to a path.
Uri uri = new Uri(fname);
fname = uri.LocalPath;
this.Properties["ArbitraryArgName"] = fname;
}
catch
{
// For some reason, this couldn't be read as a URI.
// Do what you must...
}
}
string procName = Process.GetCurrentProcess().ProcessName;
// get the list of all processes by the "procName"
Process[] processes = Process.GetProcessesByName(procName);
if (processes.Length > 1)
{
MessageBox.Show(procName + " already running");
//App a = new App();
//a.Shutdown();
}
else
{
}
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
base.OnStartup(e);
}
}
感谢。
伟大的!非常感谢。它工作得很好。你的代码简单易懂!感谢你的协助。 – kimtk
欢迎您! – zamoldar