2011-3-9 0:01:32
管理员
目录
1. VSTO解决方案
1.1. 简介
1.2. 访问宿主应用程序的对象模型
1.3. Word 对象模型
1.4. C#开发注意事项
2. 常见问题:
2.1. 新建Word2003 Add-in工程,关闭工程后再次打开,提示Solution升级。
2.2. 宿主Application接口中没有新建文档事件。
2.3. WordAddin按钮失去响应
2.4. 创建、获得样式时程序出错
2.5. 部署失败问题
3. 常用方法:
3.1. 获得Word编号列表
3.2. 利用反射获得添加图片对话框选择的文件的文件名
3.3. 常用枚举以wd开头
3.4. 光标移动方法
3.5. 插入公式方法。
3.6. 获得Word提供的所有对话框
4. 部署安装
5. 相关链接
VSTO 2005(SE)可以扩展Office 2003(2007),以及使用Visual Basic和Visual C#创建Office 2003外接程序来创建解决方案。
Visual Studio Tools for Office包含用于文档级自定义项和应用程序级外接程序的项目模板。如果希望代码是仅当特定文档打开时运行,可创建文档级自定义项,如果是只要Microsoft Office应用程序运行就可用,可创建应用程序级外接程序。
宿主项和宿主控件是为Visual Studio Tools for Office解决方案提供编程模型的类。即,它们使得与基于COM的Microsoft Office应用程序进行交互更像与托管对象进行交互。
宿主项为Visual Studio Tools for Office解决方案中的代码提供入口点。
若要访问宿主应用程序的对象模型,可使用ThisAddIn类的Application字段。此字段返回表示宿主应用程序当前实例的对象。ThisAddIn 类以外的代码可以使用Globals.ThisAddIn.Application 访问此字段。
1. 在Word项目中使用C#时,必须使用ref关键字传递可选参数,而且必须传递包含实际值的变量。不能向Word方法传递文本值。
解决方法:如图,取消Always upgrade to installed version of Office(图中红色方块标注处)。
2.2.宿主Application接口中没有新建文档事件。
解决方法:新建文档事件在ApplicationEvents4_Event接口中
。
原因:最常见的原因是command bar buttons没有在类级别声明。最后被GC回收,Event handlers不再连接到buttons。
解决方法:在类级别声明buttons变量。
解决方法:
1. 遍历样式集,判断样式是否存在,但效率较低。
2. 利用Try Catch,存在样式就获得该样式,不存在就创建该样式。
1. 安全策略错误
解决方法:(1)给程序集签署强命名。(2)利用SetSecurity工程(详见
部署安装)
2. 程序集语言设置错误
解决方法:右键单击WordAddin工程,选择属性,选择Application选项卡,点击Assembly Information按钮,更改Neutral Language为None。
ListTemplate oneLevelListTemplate = Application.ListGalleries[WdListGalleryType.wdNumberGallery].ListTemplates.get_Item(ref index);
private static string GetPictureName(Word.Dialog dlg)
{
System.Type dialogType = typeof(Word.Dialog);
string path = (string)dialogType.InvokeMember("Name", System.Reflection.BindingFlags.GetProperty |
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, dlg, null);
string[] str = path.Split('\\');
string pictureNameWithExt = str[str.Length - 1];
string pictureName = pictureNameWithExt.Remove(pictureNameWithExt.IndexOf('.'));
return pictureName;
}
左移6个字符示例:
unit = WdUnits.wdCharacter;
count = 6;
sel.MoveLeft(ref unit, ref count, ref missing);
object equation = "Equation.3";
object range = Application.Selection.Range;
Application.ActiveDocument.InlineShapes.AddOLEObject(ref equation, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref range);
获得插入图片对话框示例:
Word.Dialog dlg = Application.Dialogs[WdWordDialog.wdDialogInsertPicture];
如需其他对话框,可以更改代码段中红色字体部分。
首先给程序及签名,右键单击WordAddin工程,选择属性,然后点击Signing选项卡,勾选Sign the assembly。
/assemblyName="WordHelper.dll" /targetDir="[TARGETDIR]\" /solutionCodeGroupName="WordAddIn" /solutionCodeGroupDescription="Code group for WordAddin" /assemblyCodeGroupName="WordAddin" /assemblyCodeGroupDescription="Code group for WordAddin" /allUsers=[ALLUSERS]
用来给Addin程序集添加安全策略,否则插件安装后不能正常运行。(代码中红色字体文字替换为程序集名称)
在Uninstall/Rollback中添加SetSecurity工程输出文件,并设置属性中CustomActionData为
/solutionCodeGroupName="WordAddin"
最终效果如图: