-1

I'm building one software integration with one old WPF application. This WPF application have an event handler for drop event:

public void Window_Drop(object sender, DragEventArgs e)
{
   // Spaghetti code
}

The Window_Drop event take the dropped file, elaborate it and send the result to a web services.

My goal is use the current logic dropping a file inside a specific folder.

I wrote this code:

Watcher class

public class Watcher
    {
        public delegate void ActionDelegate(string fileName, string fullPath);
        private ActionDelegate Action;

        private readonly FileSystemWatcher _watcher;
        public Watcher(string path)
        {
            _watcher = new FileSystemWatcher();
            _watcher.Path = path;
            _watcher.Created += _watcher_Created;
            _watcher.EnableRaisingEvents = true;
        }

        public void SubscribeOnCreate(ActionDelegate action)
        {
            Action = action;
        }

        private void _watcher_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("Creato " + e.Name);
            Action(e.Name, e.FullPath, string.Empty);
        }
    }
}

App.cs

public partial class App : Application, ISingleInstanceApp
{
    private Watcher _watcher;

    public App()
    {
        _watcher = new Watcher(@"C:\Users\Administrator\Desktop\Monitoraggio");
        _watcher.SubscribeOnCreate(LoadFile);
    }

    private void LoadFile(string fileName, string fullPath)
    {
        var droppedFile = new DragEventArgs(); // How can I build one DragEventArgs object with dropped file?
        var currentWindow = MainWindow.AppWindow; // this is a static reference of current MainWindow
        a.Window_Drop(this, droppedFile);
    }
}

How can I build one vali DragEventArgs manually?

Every suggestion is welcome, Thanks

ilMattion
  • 1,841
  • 2
  • 24
  • 47

1 Answers1

0

You can't create an instance of the DragEventArgs class without using reflection since it has no public constructor defined.

What you should do is to refactor the Window_Drop event handler so that it takes the data that it needs from the DragEventArgs that gets created by the framework and then passes this data to a method of yours that you can also call from your LoadFile method.

So instead of trying to invoke the actual event handler, you call the same method as the event handler calls if you see what I mean.

The other, non-recommended, option would be to use reflection to create an instance of the DragEventArgs class:

Instantiating a constructor with parameters in an internal class with reflection

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Just to add another restriction why it's not that trivial to create an instance of DragEventArgs. DragEvenArgs is marked as a sealed class. So it was not intended to be derived from, thereby preventing you from creating a new subclass that you can actually instantiate. – mickeymicks Sep 03 '21 at 11:46