[英]How to add ActiveX control at run time
我正在尝试在基于C#Windows窗体的项目的用户控件中添加activeX控件。
现在,如果我从工具菜单中添加了activeX组件,则只需使用拖放操作就可以使用activeX控件。
但是,当我尝试在运行时使用C#代码添加该代码时,则会引发以下异常:
“引发了类型'System.Windows.Forms.AxHost = InvalidActiveXStateException'的异常”。
使用CreateControl()可以摆脱此异常,但是现在ActiveX控件没有出现在窗体上。
何时添加控件,以及何时在表单上添加控件?
通常,在组件初始化之后,通常会在构造函数中加载控件:
public FormRecalculation()
{
InitializeComponent();
loadDataSelector();
}
如果有任何关联的许可证密钥,则需要设置它们并将它们添加到表单上的相应容器中:
private void loadDataSelector()
{
//Initialize the DataSelector
DataSelector = new AXQDataSelector(getClsidFromProgId("QDataSelLib.QDataSel"));
if (DataSelector != null)
{
System.Reflection.FieldInfo f =
typeof(AxHost).GetField("licenseKey",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
f.SetValue(DataSelector, "license-here");
splitContainer1.Panel2.Controls.Add(DataSelector);
((System.ComponentModel.ISupportInitialize)(DataSelector)).BeginInit();
this.DataSelector.Dock = System.Windows.Forms.DockStyle.Fill;
this.DataSelector.Enabled = true;
this.DataSelector.Location = new System.Drawing.Point(0, 0);
this.DataSelector.Name = "DataSelector";
this.DataSelector.Size = new System.Drawing.Size(324, 773);
this.DataSelector.TabIndex = 0;
splitContainer1.Panel2.ResumeLayout();
((System.ComponentModel.ISupportInitialize)(DataSelector)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
else
{
return;
}
}
这实际上是用于包装好的OCX,但您知道了...
好的,经过一些更改后,代码如下所示。 在运行时,将在此处创建四个选项卡。 最初,在第一个选项卡上显示控件。 当用户单击其他选项卡上的页面时,将在这些页面上动态添加ActiveX控件。 (此代码是为.net用户控件编写的。在运行时,此用户控件已添加到表单中)
private void Populate()
{
int position;
int i = 0;
//here children in list of string type
foreach (string child in children)
{
this.productLineTabs.TabPages.Add(child);
AxSftTree treeadd = loadtree(this.productLineTabs.TabPages[i]);
this.tree.Add(treeadd);
this.tree[i].Columns = 2;
this.tree[i].set_ColumnText(0, "Col1");
this.tree[i].set_ColumnText(1, "Col2");
position = this.tree[i].AddItem(child);
i++;
}
form plv = new form();
plv.Controls.Add(this);
plv.Show();
}
private AxSftTree loadtree(TabPage tab)
{
AxSftTree treeobject = new AxSftTree();
((System.ComponentModel.ISupportInitialize)(treeobject)).BeginInit();
SuspendLayout();
tab.Controls.Add(treeobject);
treeobject.Dock = DockStyle.Fill;
ResumeLayout();
((System.ComponentModel.ISupportInitialize)(treeobject)).EndInit();
return treeobject;
}
您可以在此页面上找到有关此实现的一些详细信息: http : //newapputil.blogspot.in/2013/11/how-to-add-activex-control-at-run-time.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.