Controlling WPF in native interop - c#

I'm writing an application in native code and wish to use WPF for a user-interface library. Now, I've got the interoperation down relatively easily, but ultimately, I'm trying to write a native app, with WPF as a library, not a WPF app with a few native extensions. That said, I'm looking for an interoperation solution with certain qualities that I just can't seem to find in any examples.
Firstly, I definitely want to write my own main loop. I might perform arbitrary actions in native code and I want the ability to poll, for example, in each iteration. My application is definitely not a "sleep until you click something" application.
Secondly, I want the ability to control WPF. I want to say when WPF processes input. I want to say when it renders. I want it to make me a sammich, when I say so. This is one of the bigger problems that I have. Surely these methods must exist inside WPF, they're just not exposed anywhere that I can find them.
I've been looking into CLR hosting, but it doesn't seem to have a kind of, "Go until finished" thing that I'm looking for. Even if I cracked open a critical section or something, even from managed code there's no way to make WPF do what you want.

If I understand your question correctly, it sounds like you want to write your own main loop/message pump for WPF. I remember reading about this in a message thread a while back. It's not a full answer, but I wonder if it might point you in the right direction.
Subject: Game loops in WPF?
wondering how easy it would be to write a custom "game loop" within the WPF framework. By game loop, I mean pumping my own events on a custom Dispatcher so I can control the framerate of my app.
Answer:
You can write your own message pump. Just don't call Dispatcher.Run. You need to pump messages, and you need to call ComponentDispatcher.RaiseThreadMessage as appropriate. Use reflector to see what Dispatcher.PushFrame does.
Of course, this still may not give you what you want for a "game loop"...
Source: http://blogs.msdn.com/b/jaimer/archive/2009/06/29/wpf-discussions-090626.aspx

I think you want to look at HwndSource. It hosts a WPF GUI as a win32 control. Its all a bit tricky though and you're probably better off writing a plain WPF .net GUI app and using it to drive your native code using some form of interop. MS really didn't think of this kind of migration approach (reusing your existing code and slapping a new GUI on top) preferring to make us all rewrite all our code.
There are plenty of examples around the web. Good luck.
PS.
of course you could try the current 'gold standard' in native GUIs - Qt.

Related

Might GC.Collect() be warranted in this particular case?

Disclaimer: Yes, I know that the general answer to whether or not to use GC.Collect() is a resounding "NO!". This is the first time in several years of programming that I ever consider using it at all.
Well then, here's the situation: We have developed a C# scripting tool based on the Microsoft.CodeAnalysis.CSharp.Scripting libraries (v3.6.0). It's a Winform GUI with editor etc., not unlike others out there. We use it for the validation of integrated circuits, meaning that its primary task is interfacing lab equipment such as power supplies, pattern generators, meters and the like. For the communication to said instruments we predominantly rely on National Instrument's VISA framework, albeit not exclusively. Some devices are controlled directly via DLLs from their respective manufacturers. In general, this system is working beautifully and by now it is successfully used by quite a lot of design engineers who do not know the first thing about the intricacies of .NET and C#.
At this point I should explain that the user can simply write a method (i.e. on "top-level") and then execute it. The Roslyn-part behind this is that the input is fed to CSharpScript.Create() and then compiled. The execution of a method is done via Script.ContinueWith("method name"). Inside of such a method the user can construct an object like, say, new VISA("connection string"), which connects to the device and then communicate with the device via this object. Nothing forces him or her to care about disposing the object (i.e. closing the connection).
Now, the problem is this: recently, very sporadic crashes of the GUI application have occurred with no feedback at all from the system - the form just closes and that's it. By trial-and-error we are currently 99% sure that if all connection objects are explicitely disposed within a method, the crashes do not occur. So, rewriting the method to something like this fixes the problem:
using(var device = new VISA("connection string"))
{
device.Query("IDN?");
}
The reason why I look into the GC's direction at all is that there is no discernible correlation to any actions from the user. The guys might run such methods for an hour without a problem and then, when scrolling in the editor, when no method is currently being executed, the GUI closes without comment. And that's why I'd like to get some input from people more knowledgeable about Roslyn and the GC:
Are there known issues with this scripting library and GC? (I would very much assume that there aren't)
Since the explicit disposal of objects seem to prevent the issue, might this be one of the extremely scarce situations where the use of GC.Collect() might be warranted? (admittedly, I could not yet test whether that also prevents the problem thanks to of home office)
Any ideas what can cause a .NET application to crash without any kind of feedback and how to obtain more information about such a crash? (the scripting engine is a separate DLL, as are the device drivers; the GUI only handles the graphics)
I am fully aware that this is a rather vague description of the problem with very little source code. This is due to the fact that the application comprises of quite a lot of source code and I have no idea what might be relevant here. Also, all namespaces in the above text refer to Microsoft.CodeAnalysis.CSharp.Scripting, except for VISA, which is self-defined. Obviously, I will gladly answer any follow-up questions for getting to the bottom of this.
Thanks in advance.
Short answer: No. It's not only not warranted, it's completely missing the actual issue.
Further explanation: #canton7 instantly hit the nail on the head when writing
I'd argue that your application shouldn't crash even if a finalizer does end up being called
The root issue hid inside a 3rd party DLL in form of an, at the very least, suboptimal implementation of IDisposable. Once I zoomed in on that, it was rather easy to produce a workaround for that.
My original question is so very misguided that I'd like to state the one that I should have asked:
How do I trace a crash of my C# application when my application's logging does not show anything?
This question has been answered comprehensively in a number of posts. In my case, the crash could be seen in the Windows event log.

Proper way to provide feedback from long-running command using ReactiveUI in WPF

I have a C#/WPF/.NET 4.5 app that users will use to open certain files. The app will then go through a lot of motions - read the file, pass it trough a number of plugins and parsers. The files are potentially fairly big (>100MB) so this could take a while. I want to keep the user informed about what is going on in the UI, so in my viewmodel I have some stuff for showing current status and a progress bar.
Now I want to be cool and modern and do this using ReactiveUIs Async command support, which is completely new to me.
For the feedback messages from the load/parse process, what is the best approach? The status message and progress bar val/max values need to be set on the UI thread, pretty basic stuff. Should I implement my data loader as an IObservable, or is it somehow better to do this using for instance the MessageBus component?
Keep in mind that a user might be loading several of these huge files into the app at once, and I want the UI to remain as responsive as possible while the loading is going on.
Examples of how to go about implementing this properly would be hugely appreciated!
I checked this with The Master himself (Paul C. Betts) elsewhere, and he told me that the way to handle this would be for the app that displays the progress information to create a Subject<SomeProgressInfo> and pass this to the guys doing the actual loading/parsing. These can then push new information to the host using .OnNext().
This also helps with unit testing, where one can just provide a dummy Subject<T> that won't be subscribed to.

Why would you override wndproc

I have been looking around and haven't really seen much information on why someone would override wndproc to handle messages.
So I wondering:
Why do it?
When to do it?
Whats its general purpose in C#?
I have tried using it when seeing a serial COM plugged and unplugged from the computer, but I felt like I managed better reliance on methods I have created myself.
Other messages I see are for key-presses, cursor settings, and other various actions. This being said most of these things already have built in methods in c# libraries. So again I am back to my three main questions. Any information, opinions, examples, etc would be awesome.
WndProc() is very, very core to the way a Windows window works. It is a managed wrapper method around the window procedure, a function that used to be written in C in the olden days. It is the way you customize the behavior of a window, making it respond differently to notifications generated by the operating system or other programs.
You don't normally have a need to override it, the WndProc() method in the base class handles most of the basic notifications. Turning them into friendly .NET events, like Click etc. But that isn't complete, either because the notification is too obscure or necessarily so because it cannot know anything about the messages used by a custom window. In which case you can fall back on overriding WndProc() to intercept the message. Best example I can think of is creating a borderless window to draw a custom window frame and still giving the window normal behavior. Most easily done by intercepting messages like WM_NCHITTEST, not wrapped by .NET.
Truly grokking WndProc() requires reading Petzold's seminal book "Programming Windows". Perhaps not that easy to grasp anymore today, it does assume a basic understanding of the C language. Which was the language targeted by the winapi 30 years ago, object oriented languages were not widely used or available back then. That also otherwise explains why writing code inside WndProc() is fairly painful, there is very little abstraction and you can't really ignore pointers.
Microsoft did make an effort to retire it, starting with Windows 8 and the WinRT api. Not exactly a slamdunk success, maybe Windows 10 will give it some traction. The foundational technology that makes WinRT work under the hood is COM, a big step up from C because it can support an object model. Albeit it well hidden in the friendly language projections, COM programming is something most programmers will try to avoid :)
I have found that it is useful for processing keypress events for a UserControl.
The keypress, keyDown, or KeyUp events are quite finicky at responding from a UserControl (even with KeyPreview set to true and all that). I found that if I override WndProc() I have much more reliability of the Control processing the command.

In .NET, can I detect system focus events (C#)?

Is it possible to determine when window focus changes at the system level? I'm writing a time-tracking application, and I'd like to be able to listen for application switching (so that I can begin logging time in a given application). I've poked around the Process class for a good hour here, and while I learned quite a few useful things, I didn't find what I was looking for. I suspect I'll need to use hooks, but it's difficult finding clear documentation on the process, let alone documentation specific to what I'm asking.
See SetWindowHooksEx.
Good article, "Windows Hooks in the .NET Framework":
http://msdn.microsoft.com/en-us/magazine/cc188966.aspx

Multiple Forms and a Single Update,Will it work?

I need to make an application in .NET CF with different/single forms with a lot of drawing/animation on each forms.I would prefer to have a single update[my own for state management and so on] function so that i can manage the different states, so that my [J2ME Gaming Code] will work without much changes.I have came to some possible scenarios. Which of the one will be perfect?
Have a single form and add/delete the controls manually , then use any of the gamelooping tricks.
Create different forms with controls and call update and application.doEvents() in the main thread.[ while(isAppRunning){ UPDATE() Application.DoEvents() }
Create a update - paint loop on each of the form as required.
Any other ideas.
Please give me suggestion regarding this
If its a game then i'd drop most of the forms and work with the bare essentials, work off a bitmap if possible and render that by either overriding the main form's paint method or a control that resides within it (perhaps a panel). That will give you better performance.
The main issue is that the compact framework isn't really designed for a lot of UI fun you don't get double-buffering for free like in full framework, proper transparency is a bitch to do with WinForm controls and if you hold onto to the UI thread for a little too long you'll get serious rendering glitches. Hell you might even get those if you do too much on background threads! :O
You're never going to get optimal performance from explicitly calling Application.DoEvents, my rule of thumb is to only use that when trouble-shooting or writing little hacks in the UI.
It might be worth sticking the game on a background thread and then calling .Invoke on the control to marshal back to the main UI thread to update your display leaving the UI with plenty of time to respond while also handling user input.
User input is another reason I avoid normal winform controls, as mobile devices generally don't have many keys it's very useful to be able to remap them so I generally avoid things like TextBoxes that have preset key events/responses.
I'd also avoid using different forms as showing a new form can provide a subtle pause, I generally swap out controls to a main form to avoid this issue when writing business software.
At the end of the day it's probably worth experimenting with various techniques to see what works out for the best. Also see if you can get any tips from people who develop games on CF as I generally only do business software.
HTH!

Categories