新建ToolStripColor.h
让类ToolStripColor继承自ToolStripControlHost实现,则ToolStripColor的对象并可以作为一个MenuItem添加到一个菜单中了
示例代码如下(此代码是基于上一个随笔中自定义的颜色设置控件实现):
#pragma once
#include <string>
namespace TestDIYMenuItem {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace SelfColorControl;
/// <summary>
/// WinForm自定义菜单项:颜色设置菜单
/// </summary>
/// <remarks>
/// 基于自定义UserControl:SelfColorControl.dll
/// </remarks>
public ref class ToolStripColor : public System::Windows::Forms::ToolStripControlHost
{
public:
/// <summary>
/// 事件回调委托类型
/// </summary>
delegate void ValueChangedHandler(void);
/// <summary>
/// 时间回调句柄
/// </summary>
event ValueChangedHandler^ pCallBack;
public:
ToolStripColor() : ToolStripControlHost(CreateControlInstance())
{
InitializeComponent();
}
ToolStripColor(std::string name): ToolStripControlHost(CreateControlInstance())
{
this->Name = "asdf";
InitializeComponent();
}
public:
/// <summary>
/// 获取当前值
/// </summary>
System::Drawing::Color GetValue()
{
return colorCtrl->CurValue;
}
/// <summary>
/// 设置当前值
/// </summary>
void SetValue(System::Drawing::Color color)
{
colorCtrl->CurValue = color;
}
private:
static SelfColorControl::ColorControl^ colorCtrl = gcnew SelfColorControl::ColorControl();
static System::Windows::Forms::Control^ CreateControlInstance()
{
colorCtrl->AutoSize = false;
return colorCtrl;
}
void InitializeComponent(void)
{
colorCtrl->ValueChanged += gcnew ColorControl::ColorValueChangedHandler(this, &ToolStripColor::colorCtrl_ValueChanged);
this->AutoSize = false;
}
// <summary>
/// 手动添加,自定义控件SelfColorControl的ValueChanged响应函数
/// </summary>
void colorCtrl_ValueChanged(System::Object^ object, System::EventArgs^ e)
{
//自定义事件回调
pCallBack();
}
};
}
这样定义的自定义菜单项使用起来比较简单:
//定义一个新的菜单项,TestDIYMenuItem是ToolStripColor的命名空间,如上述代码所示
private:TestDIYMenuItem::ToolStripColor^ toolStripColor;
//new一个菜单项
this->toolStripColor = (gcnew TestDIYMenuItem::ToolStripColor());
//将新建的颜色菜单项加入菜单对象
contextMenuStrip1->Items->Add(toolStripColor);
相关参考:http://blog.163.com/elgyin@126/blog/static/1894262020105290143261/