5

我创建了一个 Visual Studio 加载项,可将表单添加到打开的解决方案中的现有项目中。

这就是我创建表单的方式:

string templatePath = sol.GetProjectItemTemplate("Form.zip", "csproj");
//sol is an EnvDTE80.Solution2

proj.ProjectItems.AddFromTemplate(templatePath, formName);
//proj is an EnvDTE.Project

之后我可以成功获取对添加表单的 ProjectItem 的引用,然后我可以获得对 System.Windows.Forms.Form 的引用,通过这个引用我可以向表单添加一个按钮,如下所示:

Button btn = new Button();

btn.Text = "my funky button";
btn.Name = "newButton";
btn.Size = new Size(150, 23);
btn.Location = new Point(30, 30);

frmNewForm.Controls.Add(btn);
//frmNewForm is a System.Windows.Forms.Form

然后按钮成功添加到表单中:

在此处输入图像描述

但是,当我尝试保存此表单时,它不会保存。我单击 Visual Studio 的 [save] 按钮,它只是没有变成灰色。即使我点击[全部保存],表格也不会被保存。然后我关闭 Visual Studio,重新打开它,然后打开我使用加载项向其中添加了新表单的项目,但新按钮根本不存在。只是一个空表格。

我什至尝试通过以下代码以编程方式保存项目和解决方案:

itemForm.Save(itemForm.Name);
//itemFrom is an EnvDTE.ProjectItem

proj.Save(proj.FullName);
//proj is an EnvDTE.Project

我认为这是因为我用来测试我的加载项的 Visual Studio 实例是一个调试实例,在我运行我的加载项后立即打开。但我尝试使用已安装的加载项(运行后自动保留),但问题仍然存在。


更新
我刚刚注意到两件事:

1)按钮只出现在窗体的设计上,其他地方都没有。它甚至不允许我选择它来查看它的属性。

它的名称不会出现在 Intellisense 中、对象列表中,甚至不会出现在表单的设计文档中。

作为测试,我手动添加了一个按钮,我可以选择这个按钮并与之交互:

在此处输入图像描述

我可以从中得到的是我没有正确添加按钮。

Then the new question regarding the button would be: How can I add a new button to a form created through EnvDTE in a way that I can interact with it in design time ?

2) While trying to see the differences from my funky button and my Manually added button, I’ve attempted something I hadn’t before with a programmatically created form: instantiate and run it.

And here's how I've done it:

MyFunkyForm frm = new MyFunkyForm ();
frm.Show();

It flashes on the screen (apparently with none of my two buttons), and the execution ends. Even if I try to do something on it’s Form_load, it’s executed, then the form flashes, and the execution is ended (the form is closed and debugging is over), as if I had called the Close() method.

Then the additional question would be: Did I skip a step while adding the form, or am I not creating it properly at all ?

4

1 回答 1

1

你正在向 ac# 项目添加一个表单,我认为你不应该像你一样单独实例化表单,但是如果你想看到它,你应该执行应用程序。

我不知道如何做到这一点,从未尝试过自己,发现了这个,希望它会有所帮助:

http://www.mztools.com/articles/2006/mz2006016.aspx

于 2011-03-04T20:59:02.683 回答