stakx is onto something with his comment:
An obvious starting point would have been to study the original source of that line of code. Where did you copy it from? Can you find the declaration of NativeMethods.SetParent
in the original source? (No need to answer, this is meant as a suggestion of what I would have done in this case.)
This is exactly the way you need to solve such problems.
The code snippet shown in the question was in fact copied from here. No, it doesn't compile when you copy and paste it into your project. It was never intended to. I wasn't trying to write a complete demo, but rather provide a brief sketch of what the required code might look like were you to write it yourself.
You do have to read the whole answer, not just the part with the light gray background. I know we're all programmers so we often think that we can understand everything just by looking at the code, but that's an unfortunate lie. I provided a link to the Windows SDK documentation for the SetParent
function; you'll have to read that documentation, understand what the function does, and then write the P/Invoke declaration so that you can call it from your C# code.
Like Kendall says, calls to native Win32 functions are placed in a static class called NativeMethods
, both by convention and by explicit recommendation from .NET design guidelines (enforced by tools such as StyleCop). My sample was following this common practice because I assumed .NET developers interested in Win32 interop would be familiar with this convention and follow it themselves when writing the P/Invoke definition.
As Nate alludes, some people find the website http://pinvoke.net/ to be a useful resource when writing P/Invoke definitions for Win32 functions. And it can often be. But you do have to make sure that you're not just copying and pasting code from there, either. I've seen a surprisingly large number of mistakes in the samples that they provide (and answered more than my fair share of Stack Overflow questions from people whose apps blew up when they used the incorrect code they copied from that website). You need to understand what the code you're using is doing and how it is supposed to work. Not only does that ensure you can catch any mistakes that it may contain, but it also keeps you from introducing serious bugs or worse, security holes, into your application.