Why would you override wndproc - c#

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.

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.

Intercept all WM_MOUSEWHEEL messages

I've been searching through the Windows API, looking for a way to intercept all WM_MOUSESCROLL messages before they hit their perspective message queues. After intercepting I need to change a few things about them and send them to a different [or the same] message queue.
I need to do this fairly efficiently as it will be running on top of a fairly large application.
Any Ideas on how I can achieve this? I've yet to find a way.
Your best bet is an unmanaged interception using a low level mouse event hook. see this MSKB article for more info.
When using MFC you can use PreTranslateMessage, or search for the WndProc function in a custom framework and see if it provides similar functionality. Otherwise the mouse hooking is good idea. Especially when you want to do it globally.

Controlling WPF in native interop

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.

How is application virtualization implemented?

I am trying to understand how software like App-V and sandboxie (http://www.sandboxie.com/) work. But for the life of me, I can't think of anything that could make this possible. How do they intercept API calls and trick the target software? If someone would say that it's just magic and pixie dust, I would believe them. Seriously though, are there any white papers that discuss solutions to this problem?
If this is possible on the CLR level then that would be good but I'm willing to go native if I have to.
Sandboxie does it by essentially injecting code into core Windows API, the same way a virus would (which is why Vista x64 prevents this behaviour, and why Sandboxie doesn't work on that OS).
Here is a project explaining API hooking. I learned how all this work by studying the sourcecode for Metamod:Source (used for SourceMod for CounterStrike:Source :) )
I don't know how MS did it, but here is the basic theory of one way to do it ...
What you want to do is hook into the system calls (similar to chaining into interrupt).
System call occurs.
Your custom intercept gets executed.
If this syscall does not need special processing, continue on. Otherwise it needs special processing and go to step 4.
Get the stack pointer, instruction pointer and all that jazz from the stack, and build a new stack frame to send you back to your custom code in user-land.
Do your massaging of data and paths and stuff in user land. This way if the underlying OS changes, this code does not have to be updated [as frequently].
After all the data massaging, execute the system call again.
Your custom interrupt executes again, but it should detect that you are calling from your user-land helper layer and pass the call on through. Some stack frame manipulation may be required to set up proper return addresses.
Regular system call executes.
When the system call returns, the stack frame should should send you back to your regular program flow.
Hope this helps.
Check out the Wikipedia page on X86 Virtualization which discusses both software virtualization (early VMWare, Wine, Sandboxie and to an extent App-V) and the more modern hardware virtualization (Hyper-V, VMWare, others).
I'm assuming you're looking specifically for software virtualization as by using .NET (or any CLR) you're already abstracting yourself away from the CPU architecture to an extent, especially with the 'AnyCPU' target.

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

Categories