Search code examples
c#.netvisual-studioenvdte

Is it possible to use VS Shortcut as a Event In c#


Looking to create a Hot Custom hot reload feature. I need to create an Event They should be able to listen to the Save command. Assume there are two projects in the same solution. Solution: Project A Class test Project B When I change something inside the project A class test and after I used Ctrl+s it should trigger a method inside Project B. I want to listen to the File save the event in the project A Test Class. is there is any way to do this.

I was tried out the Both scenario

Try method 1:-

   public virtual event EnvDTE._dispDocumentEvents_DocumentSavedEventHandler DocumentSaved;
          

           public EnvDTE.DTE DTE { get; }
           private EnvDTE.Document document; 

          document = DTE.ActiveDocument;
          DocumentSaved?.Invoke(document);

here I am getting a Null reference error. In this case, I am not sure whether I am passing the right Document to invoke the events.

Second was the

   using (var filewatcher = new FileSystemWatcher(fullpath))
            {
                // filewatcher.IncludeSubdirectories = false;
                filewatcher.InternalBufferSize = 32768;
                filewatcher.Filter = "*.cs";
                filewatcher.NotifyFilter = NotifyFilters.LastWrite;
                filewatcher.EnableRaisingEvents = true;
                filewatcher.Changed += FileChanged;
             
                Console.ReadLine();
            }

        private  void FileChanged(object sender, FileSystemEventArgs e)
    {

        Console.WriteLine($"File Changed:{e.Name}-path{e.FullPath}");
    }

this way I was able to listen to the save command if that file change outside the Visual studio. But when trying to watch the change inside Vs FileSystemWatcher could not able to catch the File modification.


Solution

  • You can subscribe to the DocumentSaved event like this:

    events = DTE.Events;
    documentEvents = events.DocumentEvents;
    documentEvents.DocumentSaved += OnDocumentSaved;
    

    Where OnDocumentSaved is your handler.