在C#中获得对已经运行的应用程序的动态访问

在C#中获得对已经运行的应用程序的动态访问

本文介绍了在C#中获得对已经运行的应用程序的动态访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。

我正在编写一段使用应用程序的ObjectAPI的代码。 API文档中的示例显示了如何动态运行应用程序的新实例。示例显示:

Hello.
I am writing a piece of code that employs ObjectAPI of an application. The API documentation has examples showing how to dynamically run a new instance of the application. The examples show:

string pathToExe = System.IO.Path.Combine(System.Environment.GetEnvironmentVariable("PROGRAMFILES"), "CompanyName", "ProductName", "app.exe");
System.Reflection.Assembly AppAssembly = System.Reflection.Assembly.LoadFrom(pathToExe);
someObject theObject= (someObject)AppAssembly.CreateInstance("someObjectTypeString");
theObject.ApplicationStart();





最后一行导致应用程序启动,并通过以下方式提供对应用程序的进一步操作theObject中可用的对象。

对象theObject实际上负责启动和退出应用程序等操作。



我的意图是:而不是创建一个新的应用程序实例(即启动它的新会话)获取已经运行的应用程序的句柄并对其执行自定义操作。

我猜AppAssembly.CreateInstance() 方法必须由其他一些方法替换,例如getInstance(),但我的搜索无法带来任何结果。



如果有人可以帮我,我会很感激。



the last line causes the application to start and further manipulation to the application is provided through objects available inside "theObject".
The object "theObject" is actually responsible for actions like starting and exiting the application.

My intention is: instead of creating a new instance of application (i.e. starting a new session of it) get handle of an already running one and perform custom actions on it.
I guess the "AppAssembly.CreateInstance()" method must be replaced by some other one such as "getInstance()" but my search could not bring any results.

I would be thankful if someone could help me.

推荐答案

public static Process RunningInstance()
     {
         Process current = Process.GetCurrentProcess();
         Process[] processes = Process.GetProcessesByName(current.ProcessName);

         //Loop through the running processes in with the same name
         foreach (Process process in processes)
         {
             //Ignore the current process
             if (process.Id != current.Id)
             {
                 //Make sure that the process is running from the exe file.
                 if (Assembly.GetExecutingAssembly().Location.
                      Replace("/", "\\") == current.MainModule.FileName)
                 {
                     //Return the other process instance.
                      return process;

                 }
             }
         }
         //No other instance was found, return null.
         return null;
     }







if (Form1.RunningInstance() != null)
           {
               MessageBox.Show("Duplicate Instance");
               //TODO:
               //Your application logic for duplicate
               //instances would go here.
               Form1.RunningInstance().Kill();
           }
           else
           {
               RunningInstance();
           }







谢谢

Mohit




Thanks
Mohit


这篇关于在C#中获得对已经运行的应用程序的动态访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:05