Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

c# - Opening a "known file type" into running instance of custom app - .NET

How would you open a file (that has a known file/app association in the registry) into a "running instance" of the application it's supposed to open in? An example would be, I have Excel open and I click on an XLS file.....the file opens up in the current Excel instance. I want to do this for a custom application...how does the eventing/messaging work that "tells" the current instance that it needs to open a file? Is there a "file watcher" that looks for a request to do so etc? Thanks..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want to do is inherit a class from WindowsFormsApplicationBase, setting the protected IsSingleInstance property to true:

// This should all be refactored to make it less tightly-coupled, obviously.
class MyWindowsApplicationBase : WindowsFormsApplicationBase
{
  internal MyWindowsApplicationBase() : base()
  {
    // This is a single instance application.
    this.IsSingleInstance = true;

    // Set to the instance of your form to run.
    this.MainForm = new MyForm();
  }
}

The Main method of your app then looks like this:

// This should all be refactored to make it less tightly-coupled, obviously.
public static void Main(string args[])
{
  // Process the args.
  <process args here>

  // Create the application base.
  MyWindowsApplicationBase appBase = new MyWindowsApplicationBase();

  // <1> Set the StartupNextInstance event handler.
  appBase.StartupNextInstance = <event handler code>;

  // Show the main form of the app.
  appBase.Run(args);
}

Note the section marked <1>. You set this up with an event handler for the StartupNextInstanceEvent. This event is fired when the next instance of your app is fired when you have a single instance application (which you specified in the constructor of MyWindowsApplicationBase). The event handler will pass an EventArgs-derived class which will have the command line arguments which you can then process in the running instance of your app.

Then, all you have to do is set the file associations normally for the file types you want your app to process, and you are set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...