• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#操作Word(1)Word对象模型

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Word对象模型  (.Net Perspective)

本文主要针对在Visual Studio中使用C# 开发关于Word的应用程序

五大对象

Application           :代表Microsoft Word应用程序本身

Document            :代表一个Word文档

Selection              :代表当前选中的区域(高亮),没有选中区域时代表光标点

Bookmarks           :书签

Range                  :代表一块区域,与Selection类似,不过一般不可见

 

下面看一下Word的对象结构图:

OK,下面是对上述几大对象的基本特性的描述,让我们对它们有一些基本的认识。

 

l  Application是Document和Selection的基类。通过Application的属性和方法,我们可以控制Word的大环境。

 

l  Document代表一个Word文档,当你新建一个Word文档或者打开一个已有的Word文档,你将创建一个Document对象,该对象被加入到Words Documents Collection中。拥有焦点的Document称为ActiveDocument,可以通过Application对象的ActiveDocument属性获得当前文档对象

 

l  Selection代表当前选中的区域,它通常是高亮显示的(例如,你要改变一段文字的字体,你首先得选    中这段文字,那么选中的这块区域就是当前文档的Selection对象所包含的区域)

 

l  Range对象也代表文档中的一块区域,它具有以下特点

 

  •   包含一个起始位置和一个结束位置
  •   它可以包含光标点,一段文本或者整个文档
  •   它包含空格,tab以及paragraph marks
  •   它可以是当前选中的区域,当然也可以不是当前选中区域
  •   它被动态创建
  •   当你在一个Range的末尾插入文本,这将扩展该Range

 

l  Bookmark对象也代表一块区域,一般使用Bookmark来标记文档中的位置,它有如下特点

 

  •   书签一般有名字
  •   Saved with the document,且文档关闭了之后书签继续存在
  •   书签通常是隐藏的,但也可以通过代码设置其为可见

 

---------------------------------------------------------------------------------------------

下面分别介绍5大对象:

1. The Application Object

通过Application对象,你可以访问Word的所有对象以及Collections。

参考更多:MSDN-Word2007-Application Object

1.1      Application对象的属性(只介绍部分,完整内容请参看MSDN)

ActiveWindow    返回一个Window对象表示拥有焦点的窗口

 

  1. // C#  
  2. public void CreateNewWindowAndTile()  
  3. {  
  4.    // Create a new window from the active document.  
  5.    Word.Window wnd = ThisApplication.ActiveWindow.NewWindow();  
  6.    
  7.    // Tile the two windows.  
  8.    Object value = Word.WdArrangeStyle.wdTiled;  
  9.    ThisApplication.Windows.Arrange(ref value);  
  10. }  
// C#
public void CreateNewWindowAndTile()
{
   // Create a new window from the active document.
   Word.Window wnd = ThisApplication.ActiveWindow.NewWindow();
 
   // Tile the two windows.
   Object value = Word.WdArrangeStyle.wdTiled;
   ThisApplication.Windows.Arrange(ref value);
}

 

tips:   The Arrange method, like many methods in Word,requires C# developers to pass one or more parameters using the "ref"keyword. This means that the parameter you pass must be stored in a variablebefore you can pass it to the method.

        In every case, you'll need to create an Object variable, assign the variable thevalue you'd like to pass to the method, and pass the variable using the ref keyword. You'll find many examples of this technique throughout this document.

---------------------------------------------------------------------------------------------------

l  ActiveDocument        当前活动文档对象

 

l  ActivePrinter             当前活动打印机

 

l  ActiveWindow           当前活动窗口

 

l  Caption                     文档标题

  1. // C#设置word文档标题  
  2. public void SetApplicationCaption()   
  3. {  
  4.     // Change caption in title bar.  
  5.     ThisApplication.Caption = "My New Caption";  
  6. }  
// C#设置word文档标题
public void SetApplicationCaption() 
{
    // Change caption in title bar.
    ThisApplication.Caption = "My New Caption";
}

l  CapsLock   返回大小写锁定键状态

  1. // C#  
  2. public void CapsLockOn()   
  3. {  
  4.     MessageBox.Show(ThisApplication.CapsLock.ToString());  
  5. }  
// C#
public void CapsLockOn() 
{
    MessageBox.Show(ThisApplication.CapsLock.ToString());
}

 

l  DisplayAlerts 用于设置在代码允许时如何处理警告,它有三种选项:       

1.wdAlertsAll                                显示所有消息和警告(默认)

2.wdAlertsMessageBox                 仅显示消息框

3.wdAlertsNone                             忽略任何警告

下面是该属性的常见用法:

  1. // C#  
  2. public void DisplayAlerts()   
  3. {  
  4.     // Turn off display of messages and alerts.  
  5.     try   
  6.     {  
  7.         ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;  
  8.         // Your code runs here without any alerts.  
  9.         // . . .code doing something here.  
  10.    
  11.     }   
  12.     catch (Exception ex)  
  13.     {  
  14.         // Do something with your exception.  
  15.    
  16.     }   
  17.     finally   
  18.     {  
  19.         // Turn alerts on again when done.  
  20.         ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsAll;  
  21.     }  
  22. }  
// C#
public void DisplayAlerts() 
{
    // Turn off display of messages and alerts.
    try 
    {
        ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
        // Your code runs here without any alerts.
        // . . .code doing something here.
 
    } 
    catch (Exception ex)
    {
        // Do something with your exception.
 
    } 
    finally 
    {
        // Turn alerts on again when done.
        ThisApplication.DisplayAlerts = Word.WdAlertLevel.wdAlertsAll;
    }
}

 

 

l  DisplayStatusBar      可以读/写;用于表示是否显示状态栏

  1. // C#  
  2. public void ToggleStatusBar()   
  3. {  
  4.     // Toggle display of the status bar.  
  5.     bool bln = ThisApplication.DisplayStatusBar;  
  6.     ThisApplication.DisplayStatusBar = !bln;  
  7. }  
// C#
public void ToggleStatusBar() 
{
    // Toggle display of the status bar.
    bool bln = ThisApplication.DisplayStatusBar;
    ThisApplication.DisplayStatusBar = !bln;
}

 

l  Path           返回当前应用程序的路径

  1. // C#  
  2. MessageBox.Show(ThisApplication.Path);  
// C#
MessageBox.Show(ThisApplication.Path);

 

l  Selection    只读对象,表示当前选择的区域(也可以表示光标点位置)

 

l  UserName  读或写用户名

  1. // C#  
  2. public void ChangeUserName()   
  3. {  
  4.     string  str = ThisApplication.UserName;  
  5.     MessageBox.Show(str);  
  6.    
  7.     // Change UserName.  
  8.     ThisApplication.UserName = "Dudley";  
  9.     MessageBox.Show(ThisApplication.UserName);  
  10.     // Restore original UserName.  
  11.     ThisApplication.UserName = str;  
  12. }  
// C#
public void ChangeUserName() 
{
    string  str = ThisApplication.UserName;
    MessageBox.Show(str);
 
    // Change UserName.
    ThisApplication.UserName = "Dudley";
    MessageBox.Show(ThisApplication.UserName);
    // Restore original UserName.
    ThisApplication.UserName = str;
}

l  Visible        只有为true时才可见

  1. // C#  
  2. try   
  3. {  
  4.     ThisApplication.Visible = false;  
  5.     // Do whatever it is, invisibly.  
  6. }   
  7. catch (Exception ex)  
  8. {  
  9.     // Your exception handler here.  
  10. }   
  11. finally   
  12. {  
  13.     ThisApplication.Visible = true;  
  14. }  
// C#
try 
{
    ThisApplication.Visible = false;
    // Do whatever it is, invisibly.
} 
catch (Exception ex)
{
    // Your exception handler here.
} 
finally 
{
    ThisApplication.Visible = true;
}

 

1.2      Application对象的方法

 

l  CheckSpelling 检查拼写

 

l  Help 弹出帮助对话框,有三种:WdHelp,WdHelpAbout,WdHelpSearch

  1. // C#  
  2. public void DisplayHelpAbout()   
  3. {  
  4.     Object value = Word.WdHelpType.wdHelpAbout;  
  5.     ThisApplication.Help(ref value);  
  6. }  
// C#
public void DisplayHelpAbout() 
{
    Object value = Word.WdHelpType.wdHelpAbout;
    ThisApplication.Help(ref value);
}

 

l  Move         移动窗口

l  Resize        改变窗口大小

  1. // C#  
  2. public void MoveAndResizeWindow()   
  3. {  
  4.     // None of this will work if the window is   
  5.     // maximized or minimized.  
  6.     ThisApplication.ActiveWindow.WindowState =   
  7.         Word.WdWindowState.wdWindowStateNormal;  
  8.    
  9.     // Position at upper left corner.  
  10.     ThisApplication.Move(0, 0);  
  11.    
  12.     // Size to 300 x 600 points.  
  13.     ThisApplication.Resize(300, 600);  
  14. }  
// C#
public void MoveAndResizeWindow() 
{
    // None of this will work if the window is 
    // maximized or minimized.
    ThisApplication.ActiveWindow.WindowState = 
        Word.WdWindowState.wdWindowStateNormal;
 
    // Position at upper left corner.
    ThisApplication.Move(0, 0);
 
    // Size to 300 x 600 points.
    ThisApplication.Resize(300, 600);
}

 

l  Quit           退出Word,可以带参数WdSaveOptions:三个可选值分别是:      

1.wdSaveChanges

        2.wdPromptToSaveChanges

        3.wdDoNotSaveChanges

  1. // C#  
  2. // Automatically save changes.  
  3. Object saveChanges     = Word.WdSaveOptions.wdSaveChanges;  
  4. Object originalFormat  = Type.Missing;  
  5. Object routeDocument   = Type.Missing;  
  6. ThisApplication.Quit(  ref saveChanges,   
  7.                        ref originalFormat,   
  8.                        ref routeDocument);  
  9.    
  10. // Prompt to save changes.  
  11. saveChanges    = Word.WdSaveOptions.wdPromptToSaveChanges;  
  12. originalFormat  = Type.Missing;  
  13. routeDocument  = Type.Missing;  
  14. ThisApplication.Quit(  ref saveChanges,   
  15.                        ref originalFormat,   
  16.                        ref routeDocument);  
  17.    
  18. // Quit without saving changes.  
  19. saveChanges    = Word.WdSaveOptions.wdDoNotSaveChanges;  
  20. originalFormat  = Type.Missing;  
  21. routeDocument  = Type.Missing;  
  22. ThisApplication.Quit(  ref saveChanges,   
  23.                        ref originalFormat,   
  24.                        ref routeDocument);  
// C#
// Automatically save changes.
Object saveChanges     = Word.WdSaveOptions.wdSaveChanges;
Object originalFormat  = Type.Missing;
Object routeDocument   = Type.Missing;
ThisApplication.Quit(  ref saveChanges, 
                       ref originalFormat, 
                       ref routeDocument);
 
// Prompt to save changes.
saveChanges    = Word.WdSaveOptions.wdPromptToSaveChanges;
originalFormat  = Type.Missing;
routeDocument  = Type.Missing;
ThisApplication.Quit(  ref saveChanges, 
                       ref originalFormat, 
                       ref routeDocument);
 
// Quit without saving changes.
saveChanges    = Word.WdSaveOptions.wdDoNotSaveChanges;
originalFormat  = Type.Missing;
routeDocument  = Type.Missing;
ThisApplication.Quit(  ref saveChanges, 
                       ref originalFormat, 
                       ref routeDocument);

 

2. The Document Object

     使用Document对象允许你对一个文档进行操作,同时由于Documents Collection的存在,你可以操作所有已经打开的文档。

参考更多:MSDN-Word2007-Document Object

2.1        Document Object Collections

一个文档可以包含一下几类对象:

 

  • l  Characters
  • l  Words
  • l  Sentences
  • l  Paragraphs
  • l  Sections
  • l  Headers/Footers 

 

2.2 引用文档

   你可以引用一个Documents Collection中的Document对象。引用的方法是使用索引(1-based),例如,如下代码引用了collection中的第一个文档

  1. // C#  
  2. Word.Document doc = (Word.Document) ThisApplication.Documents[1];  
// C#
Word.Document doc = (Word.Document) ThisApplication.Documents[1];

当然,你也可以通过文档的名字来引用它

  1. // C#  
  2. Word.Document doc =   
  3.     (Word.Document) ThisApplication.Documents["MyDoc.doc"];  
// C#
Word.Document doc = 
    (Word.Document) ThisApplication.Documents["MyDoc.doc"];

 

2.3        打开,关闭与新建文档

 

l  Add           新建word文档  

  1. // C#  
  2. // Create a new document based on Normal.dot.  
  3. Object template = Type.Missing;  
  4. Object newTemplate = Type.Missing;  
  5. Object documentType = Type.Missing;  
  6. Object visible = Type.Missing;   
  7.    
  8. ThisApplication.Documents.Add(   
  9.   ref template, ref newTemplate, ref documentType, ref visible);  
// C#
// Create a new document based on Normal.dot.
Object template = Type.Missing;
Object newTemplate = Type.Missing;
Object documentType = Type.Missing;
Object visible = Type.Missing; 
 
ThisApplication.Documents.Add( 
  ref template, ref newTemplate, ref documentType, ref visible);

 

l  Open 打开word文档

  1. // C#  
  2. Object filename = @"C:\Test\MyNewDocument";  
  3. Object confirmConversions = Type.Missing;  
  4. Object readOnly = Type.Missing;  
  5. Object addToRecentFiles = Type.Missing;  
  6. Object passwordDocument = Type.Missing;  
  7. Object passwordTemplate = Type.Missing;  
  8. Object revert = Type.Missing;  
  9. Object writePasswordDocument = Type.Missing;  
  10. Object writePasswordTemplate = Type.Missing;  
  11. Object format = Type.Missing;  
  12. Object encoding = Type.Missing;  
  13. Object visible = Type.Missing;  
  14. Object openConflictDocument = Type.Missing;  
  15. Object openAndRepair  = Type.Missing;  
  16. Object documentDirection = Type.Missing;  
  17. Object noEncodingDialog = Type.Missing;  
  18.    
  19. ThisApplication.Documents.Open(ref filename,   
  20.     ref confirmConversions, ref readOnly, ref addToRecentFiles,   
  21.     ref passwordDocument, ref passwordTemplate, ref revert,   
  22.     ref writePasswordDocument, ref writePasswordTemplate,   
  23.     ref format, ref encoding, ref visible, ref openConflictDocument,   
  24.     ref openAndRepair , ref documentDirection, ref noEncodingDialog);  
// C#
Object filename = @"C:\Test\MyNewDocument";
Object confirmConversions = Type.Missing;
Object readOnly = Type.Missing;
Object addToRecentFiles = Type.Missing;
Object passwordDocument = Type.Missing;
Object passwordTemplate = Type.Missing;
Object revert = Type.Missing;
Object writePasswordDocument = Type.Missing;
Object writePasswordTemplate = Type.Missing;
Object format = Type.Missing;
Object encoding = Type.Missing;
Object visible = Type.Missing;
Object openConflictDocument = Type.Missing;
Object openAndRepair  = Type.Missing;
Object documentDirection = Type.Missing;
Object noEncodingDialog = Type.Missing;
 
ThisApplication.Documents.Open(ref filename, 
    ref confirmConversions, ref readOnly, ref addToRecentFiles, 
    ref passwordDocument, ref passwordTemplate, ref revert, 
    ref writePasswordDocument, ref writePasswordTemplate, 
    ref format, ref encoding, ref visible, ref openConflictDocument, 
    ref openAndRepair , ref documentDirection, ref noEncodingDialog);

 

l  Save 保存word文档

  1. // 保存所有文档  
  2. Object noPrompt = true;  
  3. Object originalFormat = Type.Missing;  
  4. ThisApplication.Documents.Save(ref noPrompt, ref originalFormat);  
  5.    
  6. // C#保存当前文档  
  7. ThisApplication.ActiveDocument.Save();  
  8.    
// 保存所有文档
Object noPrompt = true;
Object originalFormat = Type.Missing;
ThisApplication.Documents.Save(ref noPrompt, ref originalFormat);
 
// C#保存当前文档
ThisApplication.ActiveDocument.Save();
 

 

  1. // 保存指定名称的文档  
  2. Object file = "MyNewDocument.doc";  
  3. ThisApplication.Documents.get_Item(ref file).Save();  
// 保存指定名称的文档
Object file = "MyNewDocument.doc";
ThisApplication.Documents.get_Item(ref file).Save();

 

l  SaveAs 另存为

  1. // C#  
  2. // Save the document. In a real application,  
  3. // you'd want to test to see if the file  
  4. // already exists. This will overwrite any previously   
  5. // existing documents.  
  6. Object fileName = @"C:\Test\MyNewDocument.doc";  
  7. Object fileFormat = Type.Missing;  
  8. Object lockComments = Type.Missing;  
  9. Object password = Type.Missing;  
  10. Object addToRecentFiles = Type.Missing;  
  11. Object writePassword = Type.Missing;  
  12. Object readOnlyRecommended = Type.Missing;  
  13. Object embedTrueTypeFonts = Type.Missing;  
  14. Object saveNativePictureFormat = Type.Missing;  
  15. Object saveFormsData = Type.Missing;  
  16. Object saveAsAOCELetter = Type.Missing;  
  17. Object encoding = Type.Missing;  
  18. Object insertLineBreaks = Type.Missing;  
  19. Object allowSubstitutions = Type.Missing;  
  20. Object lineEnding = Type.Missing;  
  21. Object addBiDiMarks = Type.Missing;  
  22.    
  23. ThisDocument.SaveAs(ref fileName, ref fileFormat, ref lockComments,   
  24.   ref password, ref addToRecentFiles, ref writePassword,   
  25.   ref readOnlyRecommended, ref embedTrueTypeFonts,   
  26.   ref saveNativePictureFormat, ref saveFormsData,   
  27.   ref saveAsAOCELetter, ref encoding, ref insertLineBreaks,   
  28.   ref allowSubstitutions, ref lineEnding, ref addBiDiMarks);  
// C#
// Save the document. In a real application,
// you'd want to test to see if the file
// already exists. This will overwrite any previously 
// existing documents.
Object fileName = @"C:\Test\MyNewDocument.doc";
Object fileFormat = Type.Missing;
Object lockComments = Type.Missing;
Object password = Type.Missing;
Object addToRecentFiles = Type.Missing;
Object writePassword = Type.Missing;
Object readOnlyRecommended = Type.Missing;
Object embedTrueTypeFonts = Type.Missing;
Object saveNativePictureFormat = Type.Missing;
Object saveFormsData = Type.Missing;
Object saveAsAOCELetter = Type.Missing;
Object encoding = Type.Missing;
Object insertLineBreaks = Type.Missing;
Object allowSubstitutions = Type.Missing;
Object lineEnding = Type.Missing;
Object addBiDiMarks = Type.Missing;
 
ThisDocument.SaveAs(ref fileName, ref fileFormat, ref lockComments, 
  ref password, ref addToRecentFiles, ref writePassword, 
  ref readOnlyRecommended, ref embedTrueTypeFonts, 
  ref saveNativePictureFormat, ref saveFormsData, 
  ref saveAsAOCELetter, ref encoding, ref insertLineBreaks, 
  ref allowSubstitutions, ref lineEnding, ref addBiDiMarks);

 

 

l  Close 关闭word文档

  1. // 关闭所有文档  
  2. Object saveChanges     = Word.WdSaveOptions.wdSaveChanges;  
  3. Object originalFormat  = Type.Missing;  
  4. Object routeDocument   = Type.Missing;  
  5. ThisApplication.Documents.Close(ref saveChanges,   
  6.                                ref originalFormat,   
  7.                                ref routeDocument);  
// 关闭所有文档
Object saveChanges     = Word.WdSaveOptions.wdSaveChanges;
Object originalFormat  = Type.Missing;
Object routeDocument   = Type.Missing;
ThisApplication.Documents.Close(ref saveChanges, 
                               ref originalFormat, 
                               ref routeDocument);

 

  1. // 关闭 active document   
  2. Object saveChanges     = Word.WdSaveOptions.wdDoNotSaveChanges;  
  3. Object originalFormat  = Type.Missing;  
  4. Object routeDocument   = Type.Missing;  
  5. ThisDocument.Close(    ref saveChanges,   
  6.                        ref originalFormat,  
  7.                        ref routeDocument);  
  8.    
  9. // Close MyNewDocument and save changes without prompting.  
  10. Object name     = "MyNewDocument.doc";  
  11. saveChanges    = Word.WdSaveOptions.wdSaveChanges;  
  12. originalFormat  = Type.Missing;  
  13. routeDocument  = Type.Missing;  
  14.    
  15. Word.Document doc = ThisApplication.Documents.get_Item(ref name);  
  16. ThisDocument.Close(    ref saveChanges,   
  17.                        ref originalFormat,   
  18.                        ref routeDocument);  
// 关闭 active document 
Object saveChanges     = Word.WdSaveOptions.wdDoNotSaveChanges;
Object originalFormat  = Type.Missing;
Object routeDocument   = Type.Missing;
ThisDocument.Close(    ref saveChanges, 
                       ref originalFormat,
                       ref routeDocument);
 
// Close MyNewDocument and save changes without prompting.
Object name     = "MyNewDocument.doc";
saveChanges    = Word.WdSaveOptions.wdSaveChanges;
originalFormat  = Type.Missing;
routeDocument  = Type.Missing;
 
Word.Document doc = ThisApplication.Documents.get_Item(ref name);
ThisDocument.Close(    ref saveChanges, 
                       ref originalFormat, 
                       ref routeDocument);

 

l  实例:遍历DocumentsCollection

  1. // C#  
  2. public void SaveUnsavedDocuments()   
  3. {  
  4.     // Iterate through the Documents collection.  
  5.     string  str;  
  6.     StringWriter  sw = new StringWriter();  
  7.    
  8.     foreach (Word.Document doc in ThisApplication.Documents)  
  9.     {  
  10.         if (!doc.Saved )   
  11.         {  
  12.             // Save the document.  
  13.             doc.Save();  
  14.             sw.WriteLine(doc.Name);  
  15.         }  
  16.     }   
  17.    
  18.     str = sw.ToString();  
  19.     if ( str == string.Empty )   
  20.     {  
  21.     str = "No documents need saving.";  
  22.     }   
  23.     MessageBox.Show(str, "SaveUnsavedDocuments");  
  24. }  
// C#
public void SaveUnsavedDocuments() 
{
    // Iterate through the Documents collection.
    string  str;
    StringWriter  sw = new StringWriter();
 
    foreach (Word.Document doc in ThisApplication.Documents)
    {
        if (!doc.Saved ) 
        {
            // Save the document.
            doc.Save();
            sw.WriteLine(doc.Name);
        }
    } 
 
    str = sw.ToString();
    if ( str == string.Empty ) 
    {
    str = "No documents need saving.";
    } 
    MessageBox.Show(str, "SaveUnsavedDocuments");
}

3. The Selection Object

 

Selection对象代表当前选择的area。在word应用程序中,假如你要让一段字符变成黑体,你必须首先选择该段文字,然后应用样式。在代码中也是同样的道理,你要首先定义selection的区域然后进行操作。你可以使用Selection对象在文档中进行选择,格式化,操作,添加文本等。

Selection对象是始终存在的,如果当前没有选择任何东西,那么它代表一个insertion point。因此,在操作Seleciton之前知道它包含的内容是非常重要的。

Tips:    Selection对象与Range对象有很多成员是类似的,它们之间的区别是Selection对象指的是现实在图形界面的区域,而Range对象代表的区域是不可见的(当然通过调用方法可以使其可见)

 

1.1      Using the Type Property

   Selection的类型有很多。比如,你要对一张表格的一列进行操作,你应该确保该列已经selected,否则会出现运行时错误。

可以通过Selection对象的 Type属性获取你需要的信息,Type属性包含一个WdSelectionType的枚举类型成员。它有如下几个值:

  • wdSelectionBlock
  • wdSelectionColumn
  • wdSelectionFrame
  • wdSelectionInlineShape   表示一幅图片
  • wdSelectionIP                    表示插入点(insertion point)
  • wdSelectionNormal          表示选中的文本或者文本和其他对象的组合
  • wdNoSelection
  • wdSelectionRow
  • wdSelectionShape

下面是Type属性的应用例子

  1. // C#  
  2. public void ShowSelectionType()   
  3. {  
  4.     string  str;  
  5.     switch (ThisApplication.Selection.Type)   
  6.     {  
  7.         case Word.WdSelectionType.wdSelectionBlock:  
  8.             str = "block";  
  9.             break;  
  10.         case Word.WdSelectionType.wdSelectionColumn:  
  11.             str = "column";  
  12.             break;  
  13.         case Word.WdSelectionType.wdSelectionFrame:  
  14.             str = "frame";  
  15.             break;  
  16.         case Word.WdSelectionType.wdSelectionInlineShape:  
  17.             str = "inline shape";  
  18.             break;  
  19.         case Word.WdSelectionType.wdSelectionIP:  
  20.             str = "insertion point";  
  21.             break;  
  22.         case Word.WdSelectionType.wdSelectionNormal:  
  23.             str = "normal text";  
  24.             break;  
  25.         case Word.WdSelectionType.wdNoSelection:  
  26.             str = "no selection";  
  27.             break;  
  28.         case Word.WdSelectionType.wdSelectionRow:  
  29.             str = "row";  
  30.             break;  
  31.         default:  
  32.             str = "(unknown)";  
  33.             break;  
  34.     }  
  35.     MessageBox.Show(str, "ShowSelectionType");  
  36. }  
// C#
public void ShowSelectionType() 
{
    string  str;
    switch (ThisApplication.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, "ShowSelectionType");
}

 

1.2      Navigating and Selecting Text

为了判断什么被选中了,你也可以采用下面的方法。

 

1.2.1  Home and End Key Method

在使用Word时,我们知道,按下键盘的HOME键将使光标移动到光标所在行的行首,按下END键将使光标移动到行尾。在代码中,可以使用模拟按键的方法将改变selection。请看下面两个函数:

HomeKey( [Unit] , [Extend] ) : 模拟按下HOME键

EndKey( [Unit] , [Extend] )   :模拟按下END键

上面的两个函数中,参数Unit有一下可选值(wdUnit类型):

l  Wdline        移动到一行的开始或结束位置(缺省值)

l  WdStory      移动到文档的开始或结束位置

l  WdColumn  移动到一列的开始或结束位置(仅针对表格)

l  WdRow       移动到一行的开始或结束位置(仅正对表格)

参数Extend的可选值(WdMovementType类型):

l  WdMove     移动selection

l  WdExtend   扩展selection。举例说明:考虑一个场景,当前选择了一行,然后调用HomeKey方法,传入参数wdStory以及wdExtend,那么该行将不被包含在新selection对象中,同样的情况如果调用EndKey方法,那么该行将会包含在新selection对象中。

 

下面的示例代码演示了:移动insertion point到文档开始出,然后使用EndKey方法选中整个文档:

  1. // C#  
  2. // Position the insertion point at the beginning   
  3. // of the document.  
  4. Object unit     = Word.WdUnits.wdStory;  
  5. Object extend   = Word.WdMovementType.wdMove;  
  6. ThisApplication.Selection.HomeKey(ref unit, ref extend);  
  7.    
  8. // Select from the insertion point to the end of the document.  
  9. unit    = Word.WdUnits.wdStory;  
  10. extend  = Word.WdMovementType.wdExtend;  
  11. ThisApplication.Selection.EndKey(ref unit, ref extend);  
// C#
// Position the insertion point at the beginning 
// of the document.
Object unit     = Word.WdUnits.wdStory;
Object extend   = Word.WdMovementType.wdMove;
ThisApplication.Selection.HomeKey(ref unit, ref extend);
 
// Select from the insertion point to the end of the document.
unit    = Word.WdUnits.wdStory;
extend  = Word.WdMovementType.wdExtend;
ThisApplication.Selection.EndKey(ref unit, ref extend);

 

1.2.2  Arrow Key Method

既然可以模拟HOME,END键,那么当然也可以模拟按下方向键。Word提供如下四个方法,其中Count参数代表移动多少个Unit。

  • MoveLeft([Unit], [Count], [Extend])
  • MoveRight([Unit], [Count], [Extend])
  • MoveUp([Unit], [Count], [Extend])
  • MoveDown([Unit], [Count], [Extend])

其中,Extend参数使用的是与END,HOME相同的枚举类型变量,它包含两个可选值:wdMove,wdExtend.

而移动单元(Unit)类型与前面的有所不同,而且针对左右


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#定义类成员发布时间:2022-07-13
下一篇:
C#多线程之所有线程执行完成后发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap