0


我想通过知道窗口句柄来找出窗口的顶级组件名称。
这在托管 C++ 代码中是这样完成的:

//handle is the window handle as int
System::Windows::Forms::Control^ c = Control::FromHandle((System::IntPtr)System::Convert::ToInt32(handle));
System::Type^ t= c->GetType();
Console::WriteLine(t->FullName);//This is the top level name of the component.

但是,我不能将托管代码用于我必须开发的解决方案。
我曾尝试将其GetClassName()用作等效项,但这只是给了我WindowsForms10.STATIC. [...]莫名其妙的东西 :)
有谁知道如何在非托管代码中完成此操作?
我知道 C++ 本身并不提供对 WinForms 的任何支持,但我希望以正确的方式获得指针。我已经看到它在一些解决方案中完成,但无法让我的代码工作:(
提前谢谢你。

4

1 回答 1

1

这可能是 WinForms 代码正在做的事情:

  1. 创建窗口时,用于SetWindowLongPtr (handle, GWL_USERDATA, value)存储对拥有该窗口的对象的引用。
  2. Control::FromHandle 调用GetWindowLongPtr (handle, GWL_USERDATA)以检索托管对象引用,然后您可以使用(GetType() 等)进行托管操作

要在本机 Win32 和 C++ 中执行此操作,请创建一个接口类,如:

class IControl
{
public:
  virtual const string &GetTypeName () = 0;
};

然后从中派生控件:

class TextBoxControl : public IControl
{
  virtual const string &GetTypeName () { return "TextBox"; }
}

然后在控件构造函数中:

TextBoxControl::TextBoxControl ()
{
   handle = CreateWindowEx (parameters to create a text box);
   SetWindowLongPtr (handle, GWL_USERDATA, this);
}

最后,给定一个窗口句柄:

string GetWindowTypeName (HWND handle)
{
  IControl *control = GetWindowLongPtr (handle, GWL_USERDATA);
  return control->GetTypeName ();
}
于 2010-12-14T16:42:53.097 回答