public partial class ThisDocument
{
private Office.CommandBarPopup MenuBarItem;
// Arbitrary Tag value for new menu item.
private const string MENU_TAG = "DEMO_CODE";
#region Manipulate Menubar
private void InitMenuBarItems()
{
// set { up Command Bars
Office.CommandBar MainMenuBar;
try
{
MainMenuBar = ThisApplication.CommandBars["Menu Bar"];
// Attempt to find the existing menu bar item.
this.MenuBarItem = (Office.CommandBarPopup)MainMenuBar.FindControl(Office.MsoControlType.msoControlPopup, missing, MENU_TAG, missing, missing);
if (this.MenuBarItem == null)
{
this.MenuBarItem = (Office.CommandBarPopup)MainMenuBar.Controls.Add(Office.MsoControlType.msoControlPopup, missing, missing, missing, missing);
this.MenuBarItem.Caption = "演示(&D)";
this.MenuBarItem.Visible = true;
this.MenuBarItem.Tag = MENU_TAG;
// Add all the sub menu items.
//HookUpMenuItem("重置文档内容","ResetDemoText");
//HookUpMenuItem("新建窗口并平铺","CreateNewWindowAndTile", true);
//HookUpMenuItem("设置程序标题", "SetApplicationCaption");
//HookUpMenuItem("切换状态栏显示", "ToggleStatusBar");
//HookUpMenuItem("显示C盘的所有DOC文件", "ListAllDocFilesOnC");
//HookUpMenuItem("更改用户名", "ChangeUserName");
//HookUpMenuItem("拼写检查", "SpellCheckString");
//HookUpMenuItem("显示“关于”对话框", "DisplayHelpAbout");
//HookUpMenuItem("移动并调整窗口", "MoveAndResizeWindow");
//HookUpMenuItem("启动邮件向导", "LaunchFaxWizard");
//HookUpMenuItem("显示“新建”对话框", "DisplayFileNewDialog");
//HookUpMenuItem("显示“用户”信息对话框", "DisplayUserInfoDialog");
//HookUpMenuItem("保存“用户”信息对话框的更改", "DisplayExecuteDialog");
//HookUpMenuItem("隐藏“页面设置”对话框", "HiddenPageSetupDialog");
//HookUpMenuItem("保存所有未保存的文档", "SaveUnsavedDocuments");
//HookUpMenuItem("显示所选内容的类型", "ShowSelectionType");
//HookUpMenuItem("在插入点插入文本", "InsertTextAtSelection");
//HookUpMenuItem("选择句子", "SelectSentence");
//HookUpMenuItem("格式化区域并取消", "FormatRangeAndUndo");
//HookUpMenuItem("操作区域中的文本", "ManipulateRangeText");
//HookUpMenuItem("创建书签", "CreateBookmarks");
//HookUpMenuItem("显示所有书签", "ListBookmarks");
//HookUpMenuItem("显示书签文本", "BookmarkText");
//HookUpMenuItem("在所选内容中查找", "FindInSelection");
//HookUpMenuItem("在区域中查找", "FindInRange");
//HookUpMenuItem("循环查找并格式化","FindInLoopAndFormat");
//HookUpMenuItem("替换", "SearchAndReplace");
//HookUpMenuItem("替换并恢复", "ReplaceAndRestoreSelection");
//HookUpMenuItem("切换“预览”对话框", "TogglePrintPreview");
//HookUpMenuItem("打印文档", "PrintOutDoc");
//HookUpMenuItem("新建表格", "CreateTable");
//HookUpMenuItem("添加表格行、列", "AddRowAndCol");
//HookUpMenuItem("更新书签文字", "BookmarkText");
//HookUpMenuItem("检查CAPSLOCK状态", "CapsLockOn");
//HookUpMenuItem("更改应用程序可视", "ChangeApplicationVisible");
//HookUpMenuItem("更改用户姓名", "ChangeUserName");
//HookUpMenuItem("关闭所有文档", "CloseAllDocuments");
//HookUpMenuItem("关闭所有文档并保存", "CloseAndSave");
//HookUpMenuItem("关闭单个文档并保存", "CloseSingleDocumentAndSave");
//HookUpMenuItem("关闭单个文档不保存", "CloseSingleDocumentWithoutSave");
//HookUpMenuItem("关闭并不保存", "CloseWithoutSave");
//HookUpMenuItem("折叠区域", "CollapseRange");
//HookUpMenuItem("计算区域字符数", "CountRangeCharacters");
//HookUpMenuItem("创建书签", "CreateBookmarks");
//HookUpMenuItem("新建文档", "CreateNewDocument");
//HookUpMenuItem("新建窗口并平铺", "CreateNewWindowAndTile");
//HookUpMenuItem("新建表格", "CreateTable");
//HookUpMenuItem("新建表格完整版", "CreateTableFull");
HookUpMenuItem("AddRowAndCol", "AddRowAndCol");
HookUpMenuItem("BookmarkText", "BookmarkText");
HookUpMenuItem("CapsLockOn", "CapsLockOn");
HookUpMenuItem("ChangeApplicationVisible", "ChangeApplicationVisible");
HookUpMenuItem("ChangeUserName", "ChangeUserName");
HookUpMenuItem("CloseAllDocuments", "CloseAllDocuments");
HookUpMenuItem("CloseAllDocumentsAndSave", "CloseAllDocumentsAndSave");
HookUpMenuItem("CloseSingleDocumentAndSave", "CloseSingleDocumentAndSave");
HookUpMenuItem("CloseSingleDocumentWithoutSave", "CloseSingleDocumentWithoutSave");
HookUpMenuItem("CloseAllDocumentsWithoutSave", "CloseAllDocumentsWithoutSave");
HookUpMenuItem("CollapseRange", "CollapseRange");
HookUpMenuItem("CountRangeCharacters", "CountRangeCharacters");
HookUpMenuItem("CreateBookmarks", "CreateBookmarks");
HookUpMenuItem("CreateNewDocument", "CreateNewDocument");
HookUpMenuItem("CreateNewWindowAndTile", "CreateNewWindowAndTile");
HookUpMenuItem("CreateTable", "CreateTable");
HookUpMenuItem("CreateTableFull", "CreateTableFull");
HookUpMenuItem("CriteriaSpecify", "CriteriaSpecify");
HookUpMenuItem("DisplayAlerts", "DisplayAlerts");
HookUpMenuItem("DisplayApplicationPath", "DisplayApplicationPath");
HookUpMenuItem("DisplayExecuteDialog", "DisplayExecuteDialog");
HookUpMenuItem("DisplayFileNewDialog", "DisplayFileNewDialog");
HookUpMenuItem("DisplayHelpAbout", "DisplayHelpAbout");
HookUpMenuItem("DisplaySpellCheckDialog", "DisplaySpellCheckDialog");
HookUpMenuItem("DisplayUserInfoDialog", "DisplayUserInfoDialog");
HookUpMenuItem("DistrubeColumns", "DistrubeColumns");
HookUpMenuItem("FindInLoopAndFormat", "FindInLoopAndFormat");
HookUpMenuItem("FindInRange", "FindInRange");
HookUpMenuItem("FindInSelection", "FindInSelection");
HookUpMenuItem("FinishInitialization", "FinishInitialization");
HookUpMenuItem("FormatRangeAndUndo", "FormatRangeAndUndo");
HookUpMenuItem("HiddenPageSetupDialog", "HiddenPageSetupDialog");
HookUpMenuItem("Initialize", "Initialize");
HookUpMenuItem("InitializeDataBindings", "InitializeDataBindings");
HookUpMenuItem("InsertBeforeAfterBookmark", "InsertBeforeAfterBookmark");
HookUpMenuItem("InsertText", "InsertText");
HookUpMenuItem("InsertTextAtSelection", "InsertTextAtSelection");
HookUpMenuItem("LaunchFaxWizard", "LaunchFaxWizard");
HookUpMenuItem("ListAllDocFilesOnC", "ListAllDocFilesOnC");
HookUpMenuItem("ListBookmarks", "ListBookmarks");
HookUpMenuItem("ManipulateCell", "ManipulateCell");
HookUpMenuItem("ManipulateRangeText", "ManipulateRangeText");
HookUpMenuItem("ManipulateTable", "ManipulateTable");
HookUpMenuItem("MoveMethod", "MoveMethod");
HookUpMenuItem("MoveAndResizeWindow", "MoveAndResizeWindow");
HookUpMenuItem("MoveDownMethod", "MoveDownMethod");
HookUpMenuItem("MoveStart", "MoveStart");
HookUpMenuItem("MoveUpMethod", "MoveUpMethod");
HookUpMenuItem("OnShutdown", "OnShutdown");
HookUpMenuItem("OpenDocument", "OpenDocument");
HookUpMenuItem("PrintOutDoc", "PrintOutDoc");
HookUpMenuItem("PrintOutDocument", "PrintOutDocument");
HookUpMenuItem("PrintPreviewDocument", "PrintPreviewDocument");
HookUpMenuItem("QuitAutoSave", "QuitAutoSave");
HookUpMenuItem("QuitPromptToSave", "QuitPromptToSave");
HookUpMenuItem("QuitWithoutSave", "QuitWithoutSave");
HookUpMenuItem("ReplaceAndRestoreSelection", "ReplaceAndRestoreSelection");
HookUpMenuItem("ReplaceBookmarkText", "ReplaceBookmarkText");
HookUpMenuItem("ReplaceText", "ReplaceText");
HookUpMenuItem("ResetDemoText", "ResetDemoText");
HookUpMenuItem("RetrieveStartEnd", "RetrieveStartEnd");
HookUpMenuItem("SaveAllDocuments", "SaveAllDocuments");
HookUpMenuItem("SaveAsDocument", "SaveAsDocument");
HookUpMenuItem("SaveDocumentWithoutPrompt", "SaveDocumentWithoutPrompt");
HookUpMenuItem("SaveSingleDocument", "SaveSingleDocument");
HookUpMenuItem("SaveSpecifiedDocument", "SaveSpecifiedDocument");
HookUpMenuItem("SaveUnsavedDocuments", "SaveUnsavedDocuments");
HookUpMenuItem("SearchAndReplace", "SearchAndReplace");
HookUpMenuItem("SelectAllContentAsRange", "SelectAllContentAsRange");
HookUpMenuItem("SelectRange", "SelectRange");
HookUpMenuItem("SelectSentence", "SelectSentence");
HookUpMenuItem("SelectSentenceDirectly", "SelectSentenceDirectly");
HookUpMenuItem("SelectWholeRange", "SelectWholeRange");
HookUpMenuItem("SendArrowKeyLeft", "SendArrowKeyLeft");
HookUpMenuItem("SendArrowKeyRight", "SendArrowKeyRight");
HookUpMenuItem("SendHomeKeyBegin", "SendHomeKeyBegin");
HookUpMenuItem("SendHomeKeyEnd", "SendHomeKeyEnd");
HookUpMenuItem("SetApplicationCaption", "SetApplicationCaption");
HookUpMenuItem("SetRange", "SetRange");
HookUpMenuItem("SetVariousApplicationOptions", "SetVariousApplicationOptions");
HookUpMenuItem("ShowSelectionType", "ShowSelectionType");
HookUpMenuItem("SpellCheckString", "SpellCheckString");
HookUpMenuItem("SwapParagraph", "SwapParagraph");
HookUpMenuItem("TogglePrintPreview", "TogglePrintPreview");
HookUpMenuItem("ToggleStatusBar", "ToggleStatusBar");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void HookUpMenuItem(string strCaption,string strProcToCall)
{
HookUpMenuItem(strCaption ,strProcToCall , false);
}
private void HookUpMenuItem(string strCaption, string strProcToCall, bool BeginNewGroup)
{
Office.CommandBarButton cbb = CreateButton(strCaption );
cbb.Tag = strProcToCall;
cbb.BeginGroup = BeginNewGroup;
cbb.Click += new Office._CommandBarButtonEvents_ClickEventHandler(MenuItem_Click);
}
private void MenuItem_Click(Office.CommandBarButton Ctrl, ref bool CancelDefault)
{
// Use Reflection, given the name of the procedure, to call the
// procedure whose name is stored in the button's Tag property.
// It's ugly, but it works.
try
{
Type t = typeof(ThisDocument );
MethodInfo m = t.GetMethod(Ctrl.Tag);
m.Invoke(this, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
private Office.CommandBarButton CreateButton(string Caption)
{
Office.CommandBarButton cbb = null;
try
{
cbb = (Office.CommandBarButton)this.MenuBarItem.Controls.Add(Office.MsoControlType.msoControlButton, missing,missing, missing, true);
cbb.Caption = Caption;
cbb.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return cbb;
}
private void RemoveDemoMenuItem()
{
try
{
Office.CommandBar MainMenuBar = ThisApplication.CommandBars["Menu Bar"];
// Need to locate the custom menu item again.
this.MenuBarItem = (Office.CommandBarPopup)MainMenuBar.FindControl(
Office.MsoControlType.msoControlPopup, missing, MENU_TAG, missing, missing);
this.MenuBarItem.Delete(missing);
}
catch
{
// if there's an error, don't complain.
}
}
public void ResetDemoText()
{
try
{
string docText = @"Visual Studio Tools for the Microsoft Office System"+Environment.NewLine+@"在创建收集、分析、处理或提供信息的业务应用程序时,可以利用 Microsoft Office 2003 的强大功能。通过将功能丰富的客户端应用程序集成到业务解决方案中,不但可以使用每个桌面都提供的功能,而且最终用户也可以使用熟悉的工作环境。" + Environment.NewLine + @"Microsoft Visual Studio 2005 Tools for the Microsoft Office System 可以帮助您利用 Microsoft .NET Framework 2.0 版 中的效率增强,使用 Visual Basic 和 Visual C# 扩展 Microsoft Office Word 2003、Microsoft Office Excel 2003 和 Microsoft Office Outlook 2003。工具中包含新的 Visual Studio 项目,用于帮助您为 Office 应用程序创建自定义功能。" + Environment.NewLine + @"有关 Office 可编程技术的最新信息,请参见 Microsoft Office 开发人员中心 (http://www.microsoft.com/china/office/default.mspx)。该站点包含一些链接,指向技术文章、代码示例、下载、社区信息、支持以及有关生成自定义 Office 解决方案的其他 MSDN 文档。" + Environment.NewLine + @"本节内容:" + Environment.NewLine + @"入门 (Visual Studio Tools for Office) " + Environment.NewLine + @"提供一些链接,指向有关安装 Visual Studio Tools for Office、如何开始创建解决方案以及从早期版本以来发生了哪些更改的信息。" + Environment.NewLine + @"Visual Studio Tools for Office 解决方案的结构 " + Environment.NewLine + @"提供一些链接,指向有关 Visual Studio Tools for Office 解决方案如何工作的信息(包括有关自定义文档属性、数据模型以及运行时存储控件的信息)。" + Environment.NewLine + @"升级 Office 解决方案" + Environment.NewLine + @"包含一些链接,指向有关升级过程、升级项目中必须做的更改以及 Microsoft .NET Framework 并行安装的注意事项的信息。" + Environment.NewLine + @"在 Visual Studio 中创建 Office 解决方案 " + Environment.NewLine + @"提供一些链接,指向有关创建 Office 解决方案以及程序集在解决方案中的作用的信息。" + Environment.NewLine + @"编写 Word 和 Excel 应用程序" + Environment.NewLine + @"提供一些链接,指向有关在 Word 和 Excel 解决方案中使用托管代码的信息(包括自定义 Office 用户界面、在 Office 文档中使用控件和使用操作窗格)。" + Environment.NewLine + @"使用 Office 对象模型实现应用程序自动化 " + Environment.NewLine + @"提供一些链接,指向有关使用托管代码使 Office 解决方案自动化的信息。" + Environment.NewLine + @"Office 解决方案中的数据" + Environment.NewLine + @"提供一些链接,指向解释数据如何在 Office 解决方案中工作的主题(包括有关面向架构的编程、数据缓存和服务器端数据访问的信息)。" + Environment.NewLine + @"生成并调试 Office 项目" + Environment.NewLine + @"列出解释生成和调试 Visual Studio Tools for Office 项目和 Visual Studio 中其他类型的项目(如 Windows 窗体)之间的几处不同的主题。" + Environment.NewLine + @"Office 解决方案的疑难解答" + Environment.NewLine + @"提供一些链接,指向包含关于解决在使用 Visual Studio Tools for Office 创建 Office 解决方案时可能遇到的常见问题的提示的主题。" + Environment.NewLine + @"Office 解决方案中的安全性" + Environment.NewLine + @"包含解释 Visual Studio Tools for Office 解决方案如何合并 Microsoft .NET Framework 提供的安全功能的主题。" + Environment.NewLine + @"部署 Office 解决方案" + Environment.NewLine + @"提供一些链接,指向有关如何使 Office 解决方案可供用户使用以及在选择部署方法和设置安全性时要考虑的主要问题的信息。" + Environment.NewLine + @"Visual Studio Tools for Office 中的项目扩展性 " + Environment.NewLine + @"列出提供有关 Visual Studio Tools for Office 项目中的自动化和扩展性的信息的主题,这些信息可以用来使集成开发环境中的任务自动化以及扩展项目类型和项目项。" + "/n/r" + Environment.NewLine + @"Office 开发示例和演练" + Environment.NewLine + @"提供一些链接,指向示例应用程序和提供关于执行常见任务的分步指导的主题。" ;
Object start = 0;
Object end = this.Characters.Count;
Object styleName = "lorem";
Word.Range rng = this.Range(ref start, ref end);
rng.Text = docText;
rng.set_Style(ref styleName);
}
catch
{
// do nothing
}
}
private void ThisDocument_Startup(object sender, System.EventArgs e)
{
InitMenuBarItems();
ResetDemoText();
}
private void ThisDocument_Shutdown(object sender, System.EventArgs e)
{
RemoveDemoMenuItem();
}
#region ActiveWindow
//ActiveWindow: Returns a Window object that represents the window that has the focus. This property allows you to work with whatever window has the focus. The sample code below creates a new window based on the current document and then uses the Arrange method of a Window object to tile the two windows. Note that the Arrange method uses the WdArrangeStyle.wdTiled enumerated value. (The sample application does not create a new window based on the current document: it instead creates a new document. Because the sample uses an actions pane to provide its demonstration menu, you cannot create a new window based on the current document. That feature is unavailable when using an actions pane. Therefore, the sample simply creates a new document to demonstrate the tiling feature.)
public void CreateNewWindowAndTile()
{
// Create a new window from the active document.
Word.Window wnd = Application.ActiveWindow.NewWindow();
// Tile the two windows.
Object value = Word.WdArrangeStyle.wdTiled;
Application.Windows.Arrange(ref value);
}
#endregion
#region Application Caption
//Caption: Returns or sets the caption text for the specified document or application window. You can use the Caption property to display "My New Caption" in the document window or application title bar:
public void SetApplicationCaption()
{
// Change caption in title bar.
InputBox inputCaption = new InputBox("请输入应用程序的标题:", "", "");
if (inputCaption.ShowDialog() == DialogResult.OK)
Application.Caption = inputCaption.Value;
}
#endregion
#region CapsLock
//CapsLock: Determines whether CapsLock is turned on, returning a Boolean value. The following procedure displays the state of CapsLock:
public void CapsLockOn()
{
MessageBox.Show(Application.CapsLock.ToString());
}
#endregion
#region DisplayAlerts
//DisplayAlerts: Lets you specify how alerts are handled when code is running, using the WdAlertLevel enumeration. WdAlertlevel contains three values: wdAlertsAll, which displays all messages and alerts (the default); wdAlertsMessageBox, which displays only message boxes; and wdAlertsNone, which does not display any alerts or message boxes. When you set DisplayAlerts to wdAlertsNone, your code can execute without the user seeing any messages and alerts. When you are done, you want to ensure that DisplayAlerts gets set back to wdAlertsAll (generally, you reset this in a Finally block):
public void DisplayAlerts()
{
// Turn off display of messages and alerts.
try
{
Application.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
// Your code runs here without any alerts.
// . . .code doing something here.
MessageBox.Show("你已经取消了提示!");
}
finally
{
// Turn alerts on again when done.
Application.DisplayAlerts = Word.WdAlertLevel.wdAlertsAll;
}
}
#endregion
#region DisplayStatusBar
//Read/write, returns a Boolean indicating whether or not the status bar is displayed. Returns True if it is displayed and False if it is not. The following procedure switches the display of the status bar:
public void ToggleStatusBar()
{
// Toggle display of the status bar.
bool display = Application.DisplayStatusBar;
Application.DisplayStatusBar = !display;
}
#endregion
#region FileSearch
//Searches for files using either an absolute or a relative path. You supply the search criteria, and FileSearch returns the name of the files found in the FoundFiles collection.
public void ListAllDocFilesOnC()
{
try
{
Application.System.Cursor = Word.WdCursorType.wdCursorWait;
StringWriter sw = new StringWriter();
Office.FileSearch fs = Application.FileSearch;
fs.FileName = "*.doc";
fs.LookIn = "C://";
fs.SearchSubFolders = true;
// Select the defaults, optional in VBA:
fs.Execute(Office.MsoSortBy.msoSortByFileName,
Office.MsoSortOrder.msoSortOrderAscending, true);
foreach (String str in fs.FoundFiles)
{
sw.WriteLine(str);
}
MessageBox.Show("C盘的DOC文件如下:" + sw.ToString());
}
finally
{
Application.System.Cursor = Word.WdCursorType.wdCursorNormal;
}
}
#endregion
#region Path
//When used with the Application object, returns the path of the current application:
public void DisplayApplicationPath()
{
MessageBox.Show("Application path is:"+Application.Path);
}
#endregion
#region Options
//Returns an Options object that represents application settings for Word, allowing you to set a variety of options in your application. Many, but not all, of these options are available in the Tools | Options dialog box. The following code fragment will turn on the BackgroundSave and Overtype properties, among others. If the file is printed, any fields are automatically updated, and hidden text and field codes are printed.
public void SetVariousApplicationOptions()
{
Word.Options options = Application.Options;
MessageBox.Show("下面的程序段将把“允许后台保存”、“更新域”、“隐藏文字”、“域代码”设置为选中!");
options.BackgroundSave = true;
//options.Overtype = true;
options.UpdateFieldsAtPrint = true;
options.PrintHiddenText = true;
options.PrintFieldCodes = true;
}
#endregion
#region UserName
//Gets or sets the user name. The following procedure displays the current user's name, sets the UserName property to "Dudley" and displays the new UserName. The code then restores the original UserName.
public void ChangeUserName()
{
string str = Application.UserName;
MessageBox.Show("用户名为:" +str);
// Change UserName.
Application.UserName = "Dudley";
MessageBox.Show("更改后的用户名为:" + Application.UserName);
// Restore original UserName.
Application.UserName = str;
}
#endregion
#region Visible
//A read/write property that turns the display of the Word application itself on or off. While the Visible property is False, all open Word windows are hidden, and it will appear to the user that Word has quit and all document are closed (they are still running in the background). Therefore, if you set the Visible property to False in your code, make sure to set it to True before your procedure ends. The following code accomplishes this in the Finally block of a Try/Catch exception handler
public void ChangeApplicationVisible()
{
try
{
Application.Visible = false;
// Do work here, invisibly.
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message, "Error");
// Your exception handler here.
}
finally
{
Application.Visible = true;
}
}
#endregion
#region CheckSpelling
//Checks a string for spelling errors. Returns True if errors are found, and False if no errors. This is useful if you just want to check the spelling of some text to obtain a yes/no answer to the question "Are there any spelling errors?" It does not display the errors or allow you to correct them. The following code checks the string "Speling erors here" and displays False in a MessageBox.
public void SpellCheckString()
{
// Checks a specified string for spelling errors
//string str = "Speling erors here.";
// The CheckSpelling method takes a bunch of optional parameters, in VBA:
if (Application.CheckSpelling(this.Content.Text , ref missing,ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing))
{
MessageBox.Show(String.Format("没有找到错误!"));
}
else
{
MessageBox.Show(String.Format("发现了错误"));
}
}
#endregion
#region Help
//Displays Help dialog boxes. Specify a member of the WdHelpType enumeration to choose the particular dialog box, selecting from the following list:
// WdHelp: Displays the Microsoft Word main Help dialog box.
// WdHelpAbout: Displays the dialog box available from the Help | About Microsoft Word menu item.
// WdHelpSearch: Displays the main Help dialog box with the Answer Wizard displayed.
// The following line of code displays the Help About Microsoft Word dialog box:
public void DisplayHelpAbout()
{
Object value = Word.WdHelpType.wdHelpAbout;
Application.Help(ref value);
}
#endregion
#region Move and Resize
//Move: Moves the application's main window based on the required Left and Top arguments, which are both Integer values.
//Resize: Resizes the application's main window based on the required arguments Width and Height (in points). This example moves the application to the uppermost left corner of the screen and sizes it, too:
public void MoveAndResizeWindow()
{
// None of this will work if the window is
// maximized or minimized.
Application.ActiveWindow.WindowState =Word.WdWindowState.wdWindowStateNormal;
// Position at upper left corner.
Application.Move(0, 0);
// Size to 300 x 600 points.
Application.Resize(300, 600);
}
#endregion
#region Quit
// Quits Word. You can optionally save any open documents, passing a value from the WdSaveOptions enumeration: wdSaveChanges, wdPromptToSaveChanges, and wdDoNotSaveChanges. The following fragment shows all three different ways to quit Word:
public void QuitAutoSave()
{
// Automatically save changes.
Object saveChanges = Word.WdSaveOptions.wdSaveChanges;
ThisApplication.Quit(ref saveChanges, ref missing, ref missing);
}
public void QuitPromptToSave()
{
// Prompt to save changes.
object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
//Application.Quit(ref saveChanges, ref missing, ref missing);
ThisApplication.Quit(ref saveChanges, ref missing, ref missing);
}
public void QuitWithoutSave()
{
// Quit without saving changes.
object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
ThisApplication.Quit(ref saveChanges, ref missing, ref missing);
}
#endregion
#region SendFax
//Launches the Fax Wizard, as shown in Figure 8. The user can then step through the Wizard to complete the operation.
public void LaunchFaxWizard()
{
Application.SendFax();
}
#endregion
#region Using the Built-In Dialog Boxes in Word
//When working with Word, there are times when you need to display dialog boxes for user input. Although you can create your own, you might also want to take the approach of using the built-in dialog boxes in Word, which are exposed in the Application object's Dialogs collection. This allows you to access over 200 of the built-in dialog boxes in Word, represented as values in the WdWordDialog enumeration. To use a Dialog object in your code, declare it as a Word.Dialog:
public void DisplayFileNewDialog()
{
Word.Dialog dlg;
dlg = Application.Dialogs[Word.WdWordDialog.wdDialogFileNew];
dlg.Show(ref missing);
}
public void DisplaySpellCheckDialog()
{
Word.Dialog dlg;
dlg = Application.Dialogs[Word.WdWordDialog.wdDialogToolsSpellingAndGrammar];
dlg.Show(ref missing);
}
#endregion
#region Display
//Displays the specified built-in Word dialog box until either the user closes it or the specified amount of time has passed. It does not execute any of the actions that the dialog box normally would. You can also specify an optional time out value. The code in the following procedure uses the Display method, supplying an optional Timeout value that displays the UserInfo dialog box for approximately three seconds. If the user does not dismiss the dialog, it automatically closes
public void DisplayUserInfoDialog()
{
Word.Dialog dlg;
Object timeout = 3000;
dlg = Application.Dialogs[Word.WdWordDialog.wdDialogToolsOptionsUserInfo];
dlg.Display(ref timeout);
}
#endregion
#region Execute
//If you simply call the Display method and then the user changes values in the dialog box, those changes are not applied. You need to use the Execute method after the Display method to apply any changes the user made explicitly. Unlike the Save method that saves user changes, all changes are discarded even if the user clicks OK. The following code calls the UserInfo dialog box using Display, and then the code checks the return value of the Integer variable. If the user clicked OK (returning a value of -1), the code uses the Execute method to apply the changes:
public void DisplayExecuteDialog()
{
Word.Dialog dlg;
dlg = Application.Dialogs[Word.WdWordDialog.wdDialogToolsOptionsUserInfo];
// Wait 10 seconds for results.
Object timeout = 10000;
int value = dlg.Display(ref timeout);
// Did the user press OK?
if (value == -1)
{
dlg.Execute();
}
}
#endregion
#region Modifying Dialog Values
//Because of the way the Word dialog boxes have been designed, all the properties of the various dialogs that correspond to values of controls on the forms are available only at run time. That is, when Word loads the dialog box, it creates the various properties and adds them at run time to the appropriate objects. This type of scenario makes it difficult for developers working in a strongly typed world (as in C# and in Visual Basic with Option Strict set to On) to write code that compiles.
//For example, the Page Setup dialog box (represented by the WdWordDialog.wdDialogFilePageSetup enumeration) provides a number of properties dealing with page setup, including PageWidth, PageHeight, and so on. You want to write code like the following to access these properties:
private void invokeHelper(Word.Dialog dlg, string member, Object dlgValue)
{
// Assumes a using statement in the file:
// using System.Reflection;
Type dlgType = typeof(Word.Dialog);
dlgType.InvokeMember(member,BindingFlags.SetProperty | BindingFlags.Public |BindingFlags.Instance, null, dlg, new object[] {dlgValue.ToString()});
}
public void HiddenPageSetupDialog()
{
Word.Dialog dlg;
dlg = ThisApplication.Dialogs[Word.WdWordDialog.wdDialogFilePageSetup];
invokeHelper(dlg, "PageWidth", 3.3);
invokeHelper(dlg, "PageHeight", 6);
dlg.Execute();
}
#endregion
#region Creating a New Word Document
//When you create a new Word document, you add it to the Application's Documents collection of open Word documents. Consequently, the Add method creates a new Word document. This is the same as clicking on the New Blank Document button on the toolbar.
// Create a new document based on Normal.dot.
public void CreateNewDocument()
{
Application.Documents.Add( ref missing, ref missing, ref missing, ref missing);
}
#endregion
#region Opening an Existing Document
//The Open method opens an existing document. The basic syntax is very simple. You use the Open method, and supply the fully qualified path and file name. There are other optional arguments that you can supply, such as a password, or whether to open the document read-only, which you can find by using IntelliSense in the code window. The following code opens a document, passing only one of several optional parameters. The C# code, of course, must pass all the parameters, only supplying a real value for the FileName parameter:
public void OpenDocument()
{
OpenFileDialog OpenWord = new OpenFileDialog();
OpenWord.Filter = "Word 文件(*.doc)|*.doc|Word 文件(*.rtf)|*.rtf|文本文件(*.txt)|*.txt|";
OpenWord.InitialDirectory = "C://";
if (OpenWord.ShowDialog() ==DialogResult.OK )
{
Object filename = OpenWord.FileName ;
Application.Documents.Open(ref filename, ref missing,ref missing, ref missing, ref missing,ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing,ref missing);
}
}
#endregion
#region Saving Documents
//There are several ways to save and close documents, depending on what you want the result to be. The two methods you use to save and close documents are Save and Close, respectively. They have different results depending on how they are used. If applied to a Document object, only that document is affected. If applied to the Documents collection, all open documents are affected.
public void SaveAllDocuments()
{
ThisApplication.Documents.Save(ref missing ,ref missing );
}
public void SaveDocumentWithoutPrompt()
{
Object noPrompt = true;
Application.Documents.Save(ref noPrompt, ref missing);
}
public void SaveSingleDocument()
{
this.Save();
// or Application.ActiveDocument.Save()
}
public void SaveSpecifiedDocument()
{
Object fileIndex = 1;
Application.Documents.get_Item(ref fileIndex).Save();/*或者是文档名称*/
}
#endregion
#region SaveAs
//The SaveAs method allows you to save a document under another file name. It requires that you specify the new file name, but other arguments are optional. The following procedure saves a document with a hard coded path and file name. If a file by that name already exists in that folder, it is silently overwritten. (Note that the SaveAs method accepts several optional parameters, all of which must be satisfied in C#.)
// Save the document. In a real application,
// you want want to test to see if the file
// already exists. This will overwrite any previously
// existing documents.
public void SaveAsDocument()
{
Object fileName = @"C:/MyTestDocument.doc";
this.SaveAs(ref fileName, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing,ref missing, ref missing, ref missing);
MessageBox.Show("文件另外保存到:" + fileName);
}
#endregion
#region Closing Documents
//The Close method can be used to save documents as well as close them. You can close documents individually or close all at once.
// Closing All Documents: The Close method works similarly to the Save method when applied to the Documents collection. When called with no arguments, it prompts the user to save changes to any unsaved documents.
public void CloseAllDocuments()
{
ThisApplication.Documents.Close(ref missing, ref missing, ref missing);
}
public void CloseAllDocumentsAndSave()
{
// Closes all documents: saves with no prompt.
Object saveChanges = Word.WdSaveOptions.wdSaveChanges;
Application.Documents.Close(ref saveChanges, ref missing, ref missing);
}
public void CloseAllDocumentsWithoutSave()
{
// Closes all documents: does not save any changes.
Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
Application.Documents.Close(ref saveChanges, ref missing, ref missing);
}
public void CloseSingleDocumentWithoutSave()
{
///Close a Single Document: The code fragments listed here close the document without saving changes, and close MyNewDocument silently saving changes:
// Close the document without saving changes.
Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
this.Close(ref saveChanges, ref missing, ref missing);
}
public void CloseSingleDocumentAndSave()
{
// Close MyNewDocument and save changes without prompting.
Object name = "文档 1.doc";
object saveChanges = Word.WdSaveOptions.wdSaveChanges;
Word.Document doc = Application.Documents.get_Item(ref name);
if (doc != null)
this.Close(ref saveChanges, ref missing, ref missing);
else
MessageBox.Show("没有找到“文档 1.doc”");
}
#endregion
#region Looping Through the Documents Collection
//Most of the time you probably are not going to be interested in iterating through the entire Documents collection: you want to work with an individual document. There are occasions when you want to visit each open document and conditionally perform some operation. You can refer to a Word document in the Documents collection by its name, by its index in the collection, or you can use a For Each (in Visual Basic) or foreach (in C#) loop to iterate through the documents. Inside the loop, you can conditionally perform operations on selected files. In this example, the code walks through all open documents, and if a document has not been saved, saves it.
public void SaveUnsavedDocuments()
{
// Iterate through the Documents collection.
string str;
StringWriter sw = new StringWriter();
foreach (Word.Document doc in Application.Documents)
{
if (!doc.Saved)
{
// Save the document.
doc.Save();
sw.WriteLine(doc.Name);
}
}
str = sw.ToString();
if (str == string.Empty)
{
str = "没有需要保存的文档。";
}
MessageBox.Show("下面文档原来没有保存,现在已经被保存了!/n"+str, "保存未保存的文档");
}
#endregion
#region Using the Type Property
//There are various types of selections and it is important to know what, if anything, is selected. For example, if you are performing an operation on a column in a table, you want to ensure that the column is selected to avoid triggering a run-time error. This is easily achieved with the Type property of the Selection object. The Type property contains the following WdSelectionType enumerated values that you can use in your code to determine what is selected:
// wdSelectionBlock
// wdSelectionColumn
// wdSelectionFrame
// wdSelectionInlineShape
// wdSelectionIP
// wdSelectionNormal
// wdNoSelection
// wdSelectionRow
// wdSelectionShape
//The intended purpose for each of the enumerations is obvious given its name, for the most part, but some are a little more obscure. For example, wdSelectionIP represents the insertion point. The wdInlineShape value represents an image or a picture. The value wdSelectionNormal represents selected text, or a combination of text and other selected objects.
public void ShowSelectionType()
{
string str;
switch (Application.Selection.Type)
{
case Word.WdSelectionType.wdSelectionBlock:
str = "block";
break;
case Word.WdSelectionType.wdSelectionColumn:
str = "column";
break;
case Word.WdSelectionType.wdSelectionFrame:
str = "frame";
break;
case Word.WdSelectionType.wdSelectionInlineShape:
str = "inline shape";
break;
case Word.WdSelectionType.wdSelectionIP:
str = "insertion point";
break;
case Word.WdSelectionType.wdSelectionNormal:
str = "normal text";
break;
case Word.WdSelectionType.wdNoSelection:
str = "no selection";
break;
case Word.WdSelectionType.wdSelectionRow:
str = "row";
break;
default:
str = "(unknown)";
break;
}
MessageBox.Show(str, "显示选择内容的类型");
}
#endregion
#region Home and End Key Methods
//Using these methods also changes the selection.
//HomeKey([Unit], [Extend]): Acts as if you pressed the HOME key on the keyboard.
//EndKey([Unit], [Extend]): Acts as if you pressed the END key on the keyboard.
//You use one of the following wdUnits enumerations for the Unit argument, which determines the range of the move:
// WdLine: Move to the beginning or the end of a line. This is the default value.
// WdStory: Move to the beginning or the end of the document.
// WdColumn: Move to the beginning or end of a column. Valid for tables only.
// WdRow: Move to the beginning or the end of a row. Valid for tables only.
//You use one of the following WdMovementType enumerations for the Extend argument, which determines whether the Selection object is an extended range or the insertion point:
// WdMove: Moves the selection. The result is that the new Selection object consists of the insertion point. When used with wdLine, it moves the insertion point to the beginning or end of the line. When used with wdStory, it moves the insertion point to the beginning or end of the document.
// WdExtend: Extends the selection. The result is that the new Selection object consists of a range that extends from the insertion point to the endpoint. If the starting point is not the insertion point, the behavior varies depending on the method used. For example, if a line is currently selected and the HomeKey method is called with the wdStory and wdExtend enumerations, the line is not included in the new selection. If the EndKey method is called with the wdStory and wdExtend enumerations, the line is included in the selection. This behavior mirrors the keyboard shortcuts CTRL+SHIFT+HOME and CTRL+SHIFT+END, respectively.
// Position the insertion point at the beginning of the document.
public void SendHomeKeyBegin()
{
Object unit = Word.WdUnits.wdStory;
Object extend = Word.WdMovementType.wdMove;
Application.Selection.HomeKey(ref unit, ref extend);
}
public void SendHomeKeyEnd()
{
// Select from the insertion point to the end of the document.
object unit = Word.WdUnits.wdStory;
object extend = Word.WdMovementType.wdExtend;
Application.Selection.EndKey(ref unit, ref extend);
}
#endregion
#region Arrow Key Methods
//You can also move a selection with the following methods, each of which have a Count argument that determines the number of units to move for a given direction. These methods correspond to using the cursor arrow keys on your keyboard:
// MoveLeft([Unit], [Count], [Extend])
// MoveRight([Unit], [Count], [Extend])
// MoveUp([Unit], [Count], [Extend])
// MoveDown([Unit], [Count], [Extend])
//The Extend argument takes the same two enumerations, wdMove and wdExtend. You have a different selection of WdUnits enumerations for the Unit argument for MoveLeft and MoveRight:
// wdCharacter: Move in character increments. This is the default value.
// wdWord: Move in word increments.
// wdCell: Move in cell increments. Valid for tables only.
// wdSentence: Move in sentence increments.
// Move the insertion point left 3 characters.
public void SendArrowKeyLeft()
{
Object unit = Word.WdUnits.wdCharacter;
Object count = 3;
Object extend = Word.WdMovementType.wdMove;
Application.Selection.MoveLeft(ref unit, ref count, ref extend);
}
public void SendArrowKeyRight()
{
// Select the 3 words to the right of the insertion point.
object unit = Word.WdUnits.wdWord;
object count = 3;
object extend = Word.WdMovementType.wdExtend;
Application.Selection.MoveRight(ref unit, ref count, ref extend);
}
#endregion
#region MoveUp and MoveDown methods
//take the following enumerations for WdUnits:
// wdLine: Moves in line increments. This is the default value.
// wdParagraph: Moves in paragraph increments.
// wdWindow: Moves in window increments.
// wdScreen: Moves in screen increments
public void MoveUpMethod()
{
// Move the insertion point up one line.
Object unit = Word.WdUnits.wdLine;
Object count = 1;
Object extend = Word.WdMovementType.wdMove;
Application.Selection.MoveUp(ref unit, ref count, ref extend);
}
public void MoveDownMethod()
{
// Select the following 3 paragraphs.
object unit = Word.WdUnits.wdParagraph;
object count = 3;
object extend = Word.WdMovementType.wdMove;
Application.Selection.MoveDown(ref unit, ref count, ref extend);
}
#endregion
#region Move Method
//The Move method collapses the specified range or selection and then moves the collapsed object by the specified number of units. The following code fragment collapses the original Selection object and moves three words over. The result is an insertion point at the beginning of the third word, not the third word itself:
public void MoveMethod()
{
// Use the Move method to move 3 words.
Object unit = Word.WdUnits.wdWord;
Object count = 3;
Application.Selection.Move(ref unit, ref count);
}
#endregion
#region Inserting Text
//The simplest way to insert text in your document is to use the TypeText method of the Selection object. TypeText behaves differently depending on the user's options. The code in the following procedure declares a Selection object variable and turns off the overtype option if it is turned on. If the overtype option is activated, any text next to the insertion point is overwritten:
public void InsertTextAtSelection()
{
Word.Selection sln = Application.Selection;
// Make sure overtype is turned off.
Application.Options.Overtype = false;
// Test to see if selection an insertion point.
if (sln.Type == Word.WdSelectionType.wdSelectionIP )
{
sln.TypeText("在插入点插入。");
sln.TypeParagraph();
}
else if (sln.Type == Word.WdSelectionType.wdSelectionNormal)
{
// Move to start of selection.
if (Application.Options.ReplaceSelection)
{
Object direction = Word.WdCollapseDirection.wdCollapseStart;
sln.Collapse(ref direction);
}
sln.TypeText("在文本块前插入。");
sln.TypeParagraph();
}
else
{
// Do nothing.
}
}
#endregion
#region Range Object
#region Defining and Selecting a Range
//You can define a range in a document by using the Range method of a Document object to supply a start value and an end value. The following code creates a new Range object that includes the first seven characters in the document, including non-printing characters. It then uses the Range object's Select method to highlight the range. If you omit this line of code, the Range object is not selected in the Word user interface, but you still can manipulate it programmatically.
public void SelectRange()
{
Object start = 0;
Object end = 7;
Word.Range rng = this.Range(ref start, ref end);
rng.Select();
}
#endregion
#region Counting Characters
//The first character in a document is at character position 0, which represents the insertion point. The last character position is equal to the total number of characters in the document. You can determine the number of characters in a document by using the Characters collection's Count property. The following code selects the entire document and displays the number of characters in a MessageBox:
public int CountRangeCharacters()
{
Word.Range rng = this.Range(ref missing, ref missing);
rng.Select();
MessageBox.Show("共有字符:" + this.Characters.Count.ToString());
return this.Characters.Count;
}
#endregion
#region Setting Up Ranges
//If you do not care about the number of characters and all you want to do is to select the entire document, you can use the Document object's Select method on its Range property:
public void SelectWholeRange()
{
Word.Range rng = this.Range(ref missing, ref missing);
rng.Select();
}
#endregion
#region Select Document's Content as a Range
//If you want to, you can use the Document object's Content property to define a range that encompasses the document's main story. That is, the content of the document not including headers, footers, and so on:
public void SelectAllContentAsRange()
{
Word.Range rng = this.Content;
}
#endregion
#region Select a sentence
//You can also use the methods and properties of other objects to determine a range. The code in the next procedure takes the following actions to select the second sentence in the document:
public void SelectSentence()
{
Word.Range rng;
if (this.Sentences.Count >= 2)
{
// Supply a Start and end value for the Range.
Object start = this.Sentences[2].Start;
Object end = this.Sentences[2].End;
rng = this.Range(ref start, ref end);
rng.Select();
}
}
#endregion
#region Select a sentence directly
public void SelectSentenceDirectly()
{
if (this.Sentences.Count > 2)
{
Word.Range rng = this.Sentences[2];
rng.Select();
}
}
#endregion
#region Extending a Range
//Once you define a Range object, you can extend its current range by using its MoveStart and MoveEnd methods. The MoveStart and MoveEnd methods each take the same two arguments: Unit and Count. The Unit argument can be one of the following WdUnits enumerations:
// wdCharacter
// wdWord
// wdSentence
// wdParagraph
// wdSection
// wdStory
// wdCell
// wdColumn
// wdRow
// wdTable
public void MoveStart()
{
// Define a range of 7 characters.
Object start = 0;
Object end = 7;
Word.Range rng = this.Range(ref start, ref end);
// Move the starting position 7 characters.
Object unit = Word.WdUnits.wdCharacter;
Object count = 7;
rng.MoveStart(ref unit, ref count);
// Move the ending position 7 characters.
//unit = Word.WdUnits.wdCharacter;
//count = 7;
//rng.MoveEnd(ref unit, ref count);
}
#endregion
#region Retrieving Start and End Characters in a Range
//You can retrieve the character positions of the start and end positions of a range by retrieving the Range object's Start and End properties, as shown in the following code fragment:
public void RetrieveStartEnd()
{
object start = 0;
object end = 7;
Word.Range rng = this.Range(ref start, ref end);
MessageBox.Show(String.Format("起始: {0},结束: {1}",rng.Start, rng.End), "区域起始");
}
#endregion
#region Using SetRange to Reset a Range
//You can also use SetRange to resize an existing range. The following code sets an initial Range starting with the first seven characters in the document. Next, it uses SetRange to start the range at the second sentence and end it at the end of the fifth sentence:
public void SetRange()
{
Word.Range rng;
Object start = 0;
Object end = 7;
rng = this.Range(ref start, ref end);
if (this.Sentences.Count > 5)
{
// Reset the existing Range.
rng.SetRange(this.Sentences[2].Start, this.Sentences[5].End);
rng.Select();
}
}
#endregion
#region Formatting Text
//You can also use the Range object to format text. The steps you need to take in your code are:
// Define the range to format.
// Apply the formatting.
// Optionally select the formatted range to display it.
//The code in the sample procedure selects the first paragraph in the document and changes the font size, font name, and the alignment. It then selects the range and displays a MessageBox to pause before executing the next section of code, which calls the Document object's Undo method three times. The next code block applies the Normal Indent style and displays a MessageBox to pause the code. Then the code calls the Undo method once, and displays a MessageBox.
public void FormatRangeAndUndo()
{
// Set the Range to the first paragraph.
Word.Range rng = this.Paragraphs[1].Range;
// Change the formatting.
rng.Font.Size = 14;
rng.Font.Name = "宋体";
rng.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphCenter;
rng.Select();
MessageBox.Show("区域已经被重新格式化了!", "格式化区域并撤消");
// Undo the three previous actions.
Object times = 3;
this.Undo(ref times);
rng.Select();
MessageBox.Show("撤消了3次!", "格式化区域并撤消");
// Apply the Normal Indent style.
object index = 1;
Object style = Styles.get_Item(ref index);
rng.set_Style(ref style);
rng.Select();
//MessageBox.Show("Normal Indent style applied", "格式化区域并撤消");
// Undo a single action.
times = 1;
this.Undo(ref times);
rng.Select();
MessageBox.Show("撤消了1次", "格式化区域并撤消");
}
#endregion
#region Inserting Text
//You can use the Text property of a Range object to insert or replace text in a document. The following code fragment specifies a range that is the insertion point at the beginning of a document and inserts the text " New Text " (note the spaces) at the insertion point. The code then selects the Range, which now includes the inserted text. Figure 11 shows the results after the code has run.
public void InsertText()
{
string str = " 新插入的文本";
Object start = 0;
Object end = 0;
Word.Range rng = this.Range(ref start, ref end);
rng.Text = str;
rng.Select();
}
#endregion
#region Replacing Text in a Range
//If your range is a selection and not the insertion point, all text in the range is replaced with the inserted text. The following code creates a Range object that consists of the first 12 characters in the document. The code then replaces those characters with the string.
public void ReplaceText()
{
object start = 0;
object end = 12;
string str = "此处是被替换了的文本";
Word.Range rng = this.Range(ref start, ref end);
rng.Text = str;
rng.Select();
}
#endregion
#region Collapsing a Range or Selection
//If you are working with a Range or Selection object, you may want to change the selection to a prior insertion point to avoid overwriting existing text. Both the Range and Selection objects have a Collapse method that makes use of two WdCollapseDirection enumerated values:
// WdCollapseStart: Collapses the selection to the beginning of the selection. This is the default if you do not specify an enumeration.
// WdCollapseEnd: Collapses the selection to the beginning of the selection.
public void CollapseRange()
{
string str = "新内容";
Word.Range rng = this.Paragraphs[1].Range;
Object direction = Word.WdCollapseDirection.wdCollapseStart;
rng.Collapse(ref direction);
rng.Text = str;
rng.Select();
}
#endregion
#region Inserting Text and Dealing with Paragraph Marks
//Whenever you create a Range object based on a paragraph, all non-printing characters are included as well. The following example procedure declares two string variables and retrieves the contents of the first and second paragraphs in the document:
public void ManipulateRangeText()
{
// Retrieve contents of first and second paragraphs
}
#endregion
#region Swap paragraphs between range
//The following code creates two Range variables for the first and second paragraphs and assigns the Text property, swapping the text between the two paragraphs. The code then selects each range in turn, pausing with MessageBox statements in between so that the results are displayed. Figure 15 shows the document after the swap, with rng1 selected.
public void SwapParagraph()
{
// Swap the paragraphs.
if (this.Paragraphs.Count < 2)
return;
string str1 = this.Paragraphs[1].Range.Text;
string str2 = this.Paragraphs[2].Range.Text;
Word.Range rng1 = this.Paragraphs[1].Range;
rng1.Text = str2;
Word.Range rng2 = this.Paragraphs[2].Range;
rng2.Text = str1;
// Pause to display the results.
rng1.Select();
MessageBox.Show(rng1.Text, "操作区域文本");
rng2.Select();
MessageBox.Show(rng2.Text, "操作区域文本");
}
#endregion
#endregion Range Object
#region The Bookmark Object
//The Bookmark object is similar to the Range and Selection objects in that it represents a contiguous area in a document, with both a starting position and an ending position. You use bookmarks to mark a location in a document, or as a container for text in a document. A Bookmark object can consist of the insertion point, or be as large as the entire document. You can also define multiple bookmarks in a document. You can think of a Bookmark object as a named location in the document that is saved with the document.
//In order to make it easier to work with Word bookmarks, Visual Studio 2005 Tools for Office adds the Bookmark host control. Using a host control allows you to set properties, call methods, and react to events of bookmarks—using the built-in Bookmark class provides none of these features. When you add a bookmark to a document at design time, Visual Studio 2005 Tools for Office automatically creates a Bookmark host control at the same time. You can write code that does not take into account the Bookmark host control, but working with Word becomes a lot simpler if you take advantage of these controls. One big difference that you find is that when you use a Bookmark host control, you simply set the Text property of the control to modify the text displayed within the bookmark. If you do not add a Bookmark host control, you must take several extra steps (discussed later in this section) in order to change the text inside the bookmark and preserve the bookmark. By default, without Visual Studio 2005 Tools for Office and its Bookmark host control, Word 2003 removes the bookmark when you modify its text.
#region Creating a Bookmark
//You can, of course, create bookmarks using the Word 2003 user interface. Sometimes, however, you must create bookmarks programmatically, while an application or template is running. The Bookmarks collection exists as a member of the Document, Range, and Selection objects. The CreateBookmarks sample procedure shows how to create bookmarks in a document and use them for inserting text. This example uses the Controls.AddBookmark method of the document, which adds a Bookmark host control for each new bookmark. The Bookmark host control encapsulates the Word Bookmark class. In other words, it adds functionality, but leaves all the existing functionality intact. Your code can work with the Microsoft.Office.Interop.Word.Bookmark class, or the Microsoft.Office.Tools.Word.Bookmark host control.
//The sample code takes the following actions:
// Declares a Range and two Bookmark variables and sets the view's ShowBookmarks property to True. Setting this property causes a Bookmark object set as an insertion point to appear as a gray I-bar, and a Bookmark object set to a range of text to appear as gray brackets surrounding the bookmarked text.
public void CreateBookmarks()
{
Microsoft.Office.Tools.Word.Bookmark bookMk1;
//Microsoft.Office.Tools.Word.Bookmark bookMk2;
Object start = 0;
Object end = 10;
Word.Range rng = this.Range(ref start, ref end);
// Add a Bookmark consisting of the Range object
Object range = rng;
bookMk1 = this.Controls.AddBookmark(rng, "bookMk1");
// Display the bookmark
MessageBox.Show("bookMk1的内容:" + bookMk1.Text, "创建书签");
// Display Bookmarks
this.ActiveWindow.View.ShowBookmarks = true;
// Code removed here. . .
}
#endregion
#region Insert text before the first Bookmark
public void InsertBeforeAfterBookmark()
{
Microsoft.Office.Tools.Word.Bookmark bookMk1;
//Microsoft.Office.Tools.Word.Bookmark bookMk2;
Object start = 0;
Object end = 10;
Word.Range rng = this.Range(ref start, ref end);
// Add a Bookmark consisting of the Range object
Object range = rng;
bookMk1 = this.Controls.AddBookmark(rng, "bookMk1");
this.ActiveWindow.View.ShowBookmarks = true;
rng.InsertBefore("**在bookMk1前插入**");
// Show Bookmark text
MessageBox.Show("bookMk1 Text: " +bookMk1.Text, "CreateBookmarks");
rng.InsertAfter("**在bookMk1后插入**");
MessageBox.Show("bookMk1 Text: " + bookMk1.Text, "CreateBookmarks");
}
#endregion
#region The Bookmarks Collection
//The Bookmarks collection contains all of the bookmarks in a document. In addition, bookmarks can exist in other sections of the document, such as headers and footers. You can visit each Bookmark object and retrieve its properties. The following procedure iterates through the Bookmarks collection and displays the name of each Bookmark object in the document and its Range.Text property using the MessageBox.Show method:
public void ListBookmarks()
{
StringWriter sw = new StringWriter();
foreach (Word.Bookmark bmrk in this.Bookmarks)
{
sw.WriteLine("名称: {0},内容: {1}", bmrk.Name, bmrk.Range.Text);
}
MessageBox.Show(sw.ToString(), "书签及其内容");
}
#endregion
#region Updating the Bookmark Text Property
//Updating a Bookmark host control's text is easy. You simply assign a value to the Control's Text property. If you work with a Word bookmark directly, however, modifying the Range.Text property of the bookmark deletes the entire bookmark. There is no easy way to insert text into a standard Word bookmark so that you can retrieve the text later. The simplest solution is to use a Bookmark host control, as shown in the BookmarkText procedure. Figure 24 shows the results of running this procedure.
public void BookmarkText()
{
// Create a bookmark on the first paragraph
Word.Range rng = this.Paragraphs[1].Range;
Microsoft.Office.Tools.Word.Bookmark bkmrk = this.Controls.AddBookmark(rng, "bkMark");
// Display Bookmark
this.ActiveWindow.View.ShowBookmarks = true;
MessageBox.Show(bkmrk.Text, "BookmarkText");
// Replace the text within the Bookmark host control:
bkmrk.Text = "新的书签文本";
}
#endregion
#region Replace bookmark text
//Although you can always use a Bookmark host control rather than a Word Bookmark instance, if you do not want to use the host control, you need to find some way to preserve the bookmark yourself after you insert text. When you update the contents of a Bookmark, the solution is to reset the bookmark's Range property after modifying its text. The following procedure has a BookmarkName argument for the name of the Bookmark and a NewText argument for the string that replaces the Text property. The code declares a Range object and sets it to the Bookmark object's Range property. Replacing the Range property's Text property also replaces the text in the Bookmark, which is then re-added to the Bookmarks collection. (Remember, you only need to use this procedure if you do not want to use a Bookmark host control, which does not incur any special overhead of extra programming. This procedure is included here mostly for backward compatibility, because there is generally no reason why you would not want to use a Bookmark host control and avoid these issues.)
public void ReplaceBookmarkText(string BookmarkName, string NewText)
{
if (this.Bookmarks.Exists(BookmarkName))
{
Object name = BookmarkName;
Word.Range rng = this.Bookmarks.
get_Item(ref name).Range;
rng.Text = NewText;
Object range = rng;
this.Bookmarks.Add(BookmarkName, ref range);
}
}
#endregion
#endregion Bookmark
#region Searching and Replacing Text
//When you edit a document in the Word user interface, you probably make extensive use of the Find and Replace commands on the Edit menu. The dialog boxes displayed let you specify search criteria for the text you want to locate. The Replace command is an extension of the Find command, allowing you to replace the searched text.
//The Find object is a member of both the Selection and the Range objects, and you can use either one to search for text.
#region Finding Text with a Selection Object
//When you use a Selection object to find text, any search criteria you specify are applied only against currently selected text. If the Selection is an insertion point, the entire document is searched. When the item is found that matches the search criteria, the selection changes to highlight the found item automatically. The following procedure searches for the string "dolor," and when it finds the first one, highlights the word and displays an alert, as shown in Figure 25.
public void FindInSelection()
{
// Move selection to beginning of doc
Object unit = Word.WdUnits.wdStory;
Object extend = Word.WdMovementType.wdMove;
Application.Selection.HomeKey(ref unit, ref extend);
Word.Find fnd = Application.Selection.Find;
fnd.ClearFormatting();
Object findText = "Office";
if (fnd.Execute(ref findText, ref missing, ref missing,ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing))
{
MessageBox.Show("在所选内容中找到了“Office”!", "在所选内容中查找");
}
else
{
MessageBox.Show("所选内容中没有找到“Office”!", "在所选内容中查找");
}
}
#endregion
public void CriteriaSpecify()
{
// Use Find properties to specify search criteria.
Word.Find fnd = Application.Selection.Find;
fnd.ClearFormatting();
fnd.Forward = true;
fnd.Wrap = Word.WdFindWrap.wdFindContinue;
fnd.Text = "ipsum";
ExecuteFind(fnd);
// Use Execute method arguments to specify search criteria.
fnd = Application.Selection.Find;
fnd.ClearFormatting();
Object findText = "Office";
Object wrap = Word.WdFindWrap.wdFindContinue;
Object forward = true;
ExecuteFind(fnd, wrap, forward);
}
private Boolean ExecuteFind(Word.Find find)
{
return ExecuteFind(find, missing, missing);
}
private Boolean ExecuteFind(
Word.Find find, Object wrapFind, Object forwardFind)
{
// Simple wrapper around Find.Execute:
Object forward = forwardFind;
Object wrap = wrapFind;
return find.Execute(ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref forward, ref wrap, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing);
}
#endregion
public void FindInRange()
{
// Set the second paragraph as the search range
Word.Range rng = this.Paragraphs[2].Range;
Word.Find fnd = rng.Find;
// Clear existing formatting
fnd.ClearFormatting();
// Execute the search
fnd.Text = "Office";
if (ExecuteFind(fnd))
{
MessageBox.Show("找到了“Office”", "在区域中查找");
}
else
{
MessageBox.Show("没有找到“Office”", "在区域中查找");
}
// The word faucibus is displayed if the
// search succeeds; paragraph 2 is displayed
// if the search fails.
rng.Select();
}
#region Looping through Found Items
//The Find method also has a Found property, which returns True whenever a searched-for item is found. You can make use of this in your code, as shown in the sample procedure. The code uses a Range object to search for all occurrences of the string "lorem" in the document, changes the font color and bold properties for each match. It uses the Found property in a loop, and increments a counter each time the string is found. The code then displays the number of times the string was found in a MessageBox. The C# version of this demonstration uses the ExecuteFind method discussed previously.
public void FindInLoopAndFormat()
{
int intFound = 0;
Object start = 0;
Object end = this.Characters.Count;
Word.Range rngDoc = this.Range(ref start, ref end);
Word.Find fnd = rngDoc.Find;
// Find all instances of the word "lorem" and bold each.
fnd.ClearFormatting();
fnd.Forward = true;
fnd.Text = "Office";
ExecuteFind(fnd);
while (fnd.Found)
{
// Set the new font weight and color.
// Note that each "match" resets
// the searching range to be the found text.
rngDoc.Font.Color = Word.WdColor.wdColorRed;
rngDoc.Font.Bold = 600;
intFound++;
ExecuteFind(fnd);
}
MessageBox.Show(
String.Format("“Office”在本文中共出现了{0}次!", intFound), "循环查找");
}
#endregion
#region Replacing Text
//There are several ways to search and replace text in code. A typical scenario uses the Find object to loop through a document looking for specific text, formatting, or style. If you want to replace any of the items found, you use the Find object's Replacement property. Both the Find object and the Replacement object provide a ClearFormatting method. When you are performing a find and replace operation, you must use the ClearFormatting method of both objects. If you only use it on the Find part of the replace operation, it is likely that you may end up replacing the text with unanticipated options.
//You then use the Execute method to replace each found item. The Execute method has a WdReplace enumeration that consists of three additional values:
// wdReplaceAll: replaces all found items
// wdReplaceNone: replaces none of the found items
// wdReplaceOne: replaces the first found item
//The code in the following procedure searches and replaces all of the occurrences of the string "Lorum" with the string "Forum" in the selection. The C# version of this example uses the ExecuteReplace helper method, modeled after the ExecuteFind method discussed previously:
public void SearchAndReplace()
{
// Move selection to beginning of document.
Object unit = Word.WdUnits.wdStory;
Object extend = Word.WdMovementType.wdMove;
Application.Selection.HomeKey(ref unit, ref extend);
Word.Find fnd = Application.Selection.Find;
fnd.ClearFormatting();
fnd.Text = "Lorem";
fnd.Replacement.ClearFormatting();
fnd.Replacement.Text = "Forum";
ExecuteReplace(fnd);
}
private Boolean ExecuteReplace(Word.Find find)
{
return ExecuteReplace(find, Word.WdReplace.wdReplaceAll);
}
private Boolean ExecuteReplace(Word.Find find, Object replaceOption)
{
// Simple wrapper around Find.Execute:
Object replace = replaceOption;
return find.Execute(ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref replace,
ref missing, ref missing, ref missing,
ref missing);
}
#endregion
#region Restoring the User's Selection After a Search
//If you search and replace text in a document, you may want to restore the user's original selection after the search is completed. The code in the sample procedure makes use of two Range objects: one to store the current Selection, and one to set to the entire document to use as a search range. The search and replace operation is then performed and the user's original selection restored. The C# version of this example uses the ExecuteReplace helper method shown previously:
public void ReplaceAndRestoreSelection()
{
// Save user's original selection
Word.Range rngStart = Application.Selection.Range;
// Define search range of entire document
Object start = 0;
Object end = this.Characters.Count;
Word.Range rngSearch = this.Range(ref start, ref end);
Word.Find fnd = rngSearch.Find;
fnd.ClearFormatting();
fnd.Text = "vel";
fnd.Replacement.ClearFormatting();
fnd.Replacement.Text = "VELLO";
ExecuteReplace(fnd);
// Restore user's original selection
rngStart.Select();
}
#endregion
#region Printing
//Word possesses a rich set of built-in functionality when it comes to printing. It is very easy to work with the print engine to print entire documents or sections of documents.
#region Working with Print Preview
//You can display a document in Print Preview mode by setting the document's PrintPreview property to True:
public void PrintPreviewDocument()
{
ThisApplication.PrintPreview = true;
}
public void TogglePrintPreview()
{
ThisApplication.PrintPreview = !ThisApplication.PrintPreview;
}
#endregion
#region The PrintOut Method
//You can use the PrintOut method to send a document (or part of a document) to the printer. You can call it from an Application or Document object. The following code fragment prints the document with all of the default options:
//Argument Description
//Background Set to True to allow processing while Word prints the document
//Append Use this with the OutputFileName argument. Set to True to append the specified document to the file name specified by the OutputFileName argument. Set to False to overwrite the contents of OutputFileName.
//Range The page range. Can be any WdPrintOutRange enumeration: wdPrintAllDocument, wdPrintCurrentPage, wdPrintFromTo, wdPrintRangeOfPages, or wdPrintSelection
//OutputFileName If PrintToFile is True, this argument specifies the path and file name of the output file.
//From The starting page number when Range is set to wdPrintFromTo
//To The ending page number when Range is set to wdPrintFromTo
//Item The item to be printed. Can be any WdPrintOutItem enumeration: wdPrintAutoTextEntries, wdPrintComments, wdPrintDocumentContent, wdPrintKeyAssignments, wdPrintProperties, wdPrintStyles
//Copies The number of copies to be printed
//Pages The page numbers and page ranges to be printed, separated by commas. For example, "2, 6-10" prints page 2 and pages 6 through 10.
//PageType The type of pages to be printed. Can be any WdPrintOutPages constant: wdPrintAllPages, wdPrintEvenPagesOnly, wdPrintOddPagesOnly
//PrintToFile Set to True to send printer instructions to a file. Make sure to specify a file name with OutputFileName.
//Collate Use when printing multiple copies of a document. Set to True to print all pages of the document before printing the next copy.
//FileName Available only with the Application object. The path and file name of the document to be printed. If this argument is omitted, Word prints the document.
//ManualDuplexPrint Set to True to print a two-sided document on a printer without a duplex printing kit.
public void PrintOutDocument()
{
MessageBox.Show("以缺省参数打印!");
this.PrintOut(ref missing, ref missing,ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing,ref missing, ref missing, ref missing,ref missing, ref missing);
}
public void PrintOutDoc()
{
Object background = true;
Object append = false;
Object range = Word.WdPrintOutRange.wdPrintCurrentPage;
Object item = Word.WdPrintOutItem.wdPrintDocumentContent;
Object copies = 2;
Object pageType = Word.WdPrintOutPages.wdPrintAllPages;
Object printToFile = false;
this.PrintOut(ref background, ref append,ref range, ref missing, ref missing, ref missing,ref item, ref copies, ref missing, ref pageType,ref printToFile, ref missing, ref missing,ref missing, ref missing,ref missing, ref missing,ref missing);
}
#endregion
#endregion
#region Creating Word Tables
//The Tables collection is a member of the Document, Selection, and Range objects, which means that you can create a table in any of those contexts. You use the Add method to add a table at the specified range. The following code adds a table consisting of three rows and four columns at the beginning of the document:
public void CreateTable()
{
Object start = 0;
Object end = 0;
Word.Range rng = this.Range(ref start, ref end);
this.Tables.Add(rng, 3, 4, ref missing, ref missing);
}
#endregion
#region Working with a Table Object
//Once you create a table, Word automatically adds it to the Document object's Tables collection and you can then refer to the table by its item number, as shown in the following code fragment:
public void ManipulateTable()
{
//Each Table object also has a Range property, which allows you to set direct formatting attributes. The Style property allows you to apply one of the built-in styles to the table, as shown in the following code fragment:
if (this.Tables.Count < 2)
return;
Word.Table tbl = this.Tables[1];
tbl.Range.Font.Size = 8;
Object style = "列表型 7";
tbl.set_Style(ref style);
}
#endregion
#region The Cells Collection
//Each Table consists of a collection of Cells, with each individual Cell object representing one cell in the table. You refer to each cell by its location in the table. The following code refers to the cell located in the first row and the first column of the table, adding text and applying formatting:
public void ManipulateCell()
{
if (this.Tables.Count <1)
return;
Word.Range rng = this.Tables[1].Cell(1, 1).Range;
rng.Text = "Name";
rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
}
#endregion
#region Rows and Columns
//The cells in a table are organized into rows and columns. You can add a new row to a table by using the Add method:
public void AddRowAndCol()
{
System.Diagnostics.Debug.WriteLine(this.Tables.Count);
if (this.Tables.Count < 1)
return;
Word.Table tbl = this.Tables[1];
tbl.Rows.Add(ref missing);
tbl.Columns.Add(ref missing);
}
#endregion
#region DistributeWidth method to make them all the same width:
public void DistrubeColumns()
{
if (this.Tables.Count < 1)
return;
Word.Table tbl = this.Tables[1];
Object beforeColumn = tbl.Columns[1];
tbl.Columns.Add(ref beforeColumn);
tbl.Columns.DistributeWidth();
}
#endregion
#region Pulling it all Together
//The following example creates a Word table at the end of the document and populates it with document properties:
public void CreateTableFull()
{
// Move to start of document
Object start = 0;
Object end = 0;
Word.Range rng = this.Range(ref start, ref end);
// Insert some text and paragraph marks.
rng.InsertBefore("Document Statistics");
rng.Font.Name = "Verdana";
rng.Font.Size = 16;
rng.InsertParagraphAfter();
rng.InsertParagraphAfter();
rng.SetRange(rng.End, rng.End);
// Add the table.
Word.Table tbl = rng.Tables.Add(this.Paragraphs[2].Range, 3, 2,ref missing, ref missing);
// Format the table and apply a style
tbl.Range.Font.Size = 12;
tbl.Columns.DistributeWidth();
Object style = "Table Colorful 2";
tbl.set_Style(ref style);
// Insert text in cells
tbl.Cell(1, 1).Range.Text = "Document Property";
tbl.Cell(1, 2).Range.Text = "value";
tbl.Cell(2, 1).Range.Text = "Number of Words";
tbl.Cell(2, 2).Range.Text =
this.Words.Count.ToString();
tbl.Cell(3, 1).Range.Text = "Number of Characters";
tbl.Cell(3, 2).Range.Text =
this.Characters.Count.ToString();
tbl.Select();
}
#endregion
#region VSTO Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(this.ThisDocument_Startup);
this.BeforeClose += new System.ComponentModel.CancelEventHandler(this.ThisDocument_BeforeClose);
this.Shutdown += new System.EventHandler(this.ThisDocument_Shutdown);
}
#endregion
private void ThisDocument_BeforeClose(object sender, System.ComponentModel.CancelEventArgs e)
{
}
}