首页 > 解决方案 > 覆盖派生控件中的 CreateHandle 方法

问题描述

让我们有一个第三方 DLL 来创建一个本地窗口并返回它的句柄。

我想通过基于 System.Windows.Forms.Control 的 MyControl 类在 C# WinForms 应用程序中使用此功能。

如何正确覆盖从 Control 派生的类中的虚拟受保护方法 Control.CreateHandle?

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WinFormsApp {
  public class MyControl : Control {

    [DllImport("MyLib.dll")]
    static extern IntPtr CreateWindow();

    protected override void CreateHandle() {

      // Did to need do invoke a base.CreateHandle()?
      // However, it creates Control.Handle it self.

      var handle = CreateWindow();

      // How to associate returned handle with MyControl instance?

      (WindowTarget as NativeWindow)?.AssignHandle(handle);
    }
  }
}

标签: c#winformscontrols

解决方案


推荐阅读