-3

这些代码会将 windows 计算器设置为 windows 窗体应用程序。但问题是如何在第三行使用 NativeMethods.SetParent。它有特殊的命名空间吗?

 System.Diagnostics.Process p = System.Diagnostics.Process.Start("calc.exe");
p.WaitForInputIdle();
NativeMethods.SetParent(p.MainWindowHandle, this.Handle);

请帮我在第三行使用 NativeMethods。

任何帮助将不胜感激

4

3 回答 3

2

.NET中没有公共NativeMethods类。在NativeMethods课堂上打电话被认为是一种很好的做法,所以这可能就是您所看到的。

您需要使用 P/Invoke 来调用 Win32 API 函数。请参阅本教程

于 2012-06-01T21:46:06.173 回答
2

我想你是想在 WinForm 中“嵌入”计算器?如果是这样,请查看以下 pinvoke 方法:

    [DllImport("user32.dll")]
    internal static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

http://www.pinvoke.net/default.aspx/user32.setparent

要将计算器窗口嵌入到 WinForm(或其他控件,如 Panel)中,只需传递Control.Handle第二个参数。

于 2012-06-01T21:46:51.337 回答
0

stakx 发表了评论

一个明显的起点是研究那行代码的原始来源。你从哪里复制的?你能NativeMethods.SetParent在原始来源中找到声明吗?(无需回答,这是对我在这种情况下会做什么的建议。)

这正是您解决此类问题所需的方式。

问题中显示的代码片段实际上是从这里复制的。不,当您将其复制并粘贴到您的项目中时,它不会编译。它从来没有打算——Stack Overflow 不是一个代码编写服务。我并不是想写一个完整的演示,而是提供一个简短的草图,说明如果您自己编写所需的代码可能会是什么样子。

您必须阅读整个答案,而不仅仅是浅灰色背景的部分。我知道我们都是程序员,所以我们常常认为只要看代码就可以理解一切,但这是一个不幸的谎言。我提供了该函数的 Windows SDK 文档的链接SetParent;您必须阅读该文档,了解该函数的作用,然后编写 P/Invoke 声明,以便您可以从 C# 代码中调用它。

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.

于 2012-06-03T10:23:33.690 回答