Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 394
Josh Davis Avatar asked May 21 '15 15:05

Josh Davis


Video Answer


1 Answers

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 :)

like image 192
Hans Passant Avatar answered Oct 18 '22 15:10

Hans Passant