1

I'm trying to port an application of mine from Java to C# and I can't for the life of me wrap my head around Wpf application structure.

In Java my application runs the main() method which registers native hooks and calls launch(args) for my Application class, which sets up the GUI and starts the FXApplication. I have another thread, which is run from the GUI class (for running robot scripts) can be started and stopped with f4 and f5 respectively, hence the native hooks.

In C# I can't figure out how to achieve the same effect. Without a main method I don't understand how you initialize objects outside of the scope of the MainWindow and run other threads without coupling the GUI to everything.

  • You also have Task – paparazzo Jul 9 '18 at 15:58
3

There are two questions in there.

First is about threading. When you create a new thread, it has no knowledge about UI, irrespective where or when it was created or started. So you can easily create all your worker threads in MainWindow. But if you want those threads to update the UI, then they must do so through Dispatcher.

Second is about hooking up key-presses. For that, you would use event handler attached to KeyDown event on window. Something like this. In WPF, you don't generally need to use native hooks. If you want to use this to start and stop the worker thread, then you should handle it in UI and then "send" it to the worker thread. IMO you should not catch it in thread itself.

Another thing to point out is that you can change the application structure to better fit what you describe. WPF allows to have App.xaml as application entry point, which is what standard template is using. But that is only convenience. You can make your own Main method, create App class, set up it's UI and start it up entirely in code. No need to xaml.

  • Thanks for your reply. You cleared up quite a few things about my questions. I would like to specify that I am using native hooks because I want to make sure the hooks trigger events even if the window is not the one in focus. All of these robot scripts are going to be run while another application has focus, so wouldn't I need global hooks for that? Or is C# different from Java in that regard? – CosmicKidd Jul 9 '18 at 7:10
  • 1
    @CosmicKidd In that case you do need global hooks. But I think you should make specific question for that. And I will assume that will be more WinApi than WPF question. And It should not be an issue setting up those hooks in WPF window. – Euphoric Jul 9 '18 at 7:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.