NET Core導出word文檔(表格循環插入)


本文以一個簡單的小例子,簡述利用C#語言開發word表格相關的知識,僅供學習分享使用,如有不足之處,還請指正。

在工程中引用word的動態庫

在項目中,點擊項目名稱右鍵-->管理NuGet程序包,打開NuGet包管理器窗口,進行搜索下載即可,如下圖所示:

涉及的知識點

  1. _Application: 表示word應用程序的接口,對應的實現類是Application類。
  2. _Document:表示一個word文檔,通過_Application對應的文檔接口進行創建。
  3. Paragraph:表示一個段落,通過_Document對象的相關方法進行創建。
  4. Table:表示一個表格,通過_Document對象的相關方法進行創建。
  5. Range:表示一個區域,可以是一個段落,也可以是一個表格,也可以是一個單元格,可以Range.select()將光標移動到當前區域。
  6. 移動焦點:wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);//移動焦點

Microsoft.Office.Interop.Word中涉及的知識點:

1、WdUnits枚舉類型說明                                                                               

wdCharacter

1

字符。

wdCharacterFormatting

13

字符格式。

wdColumn

9

列。

wdItem

16

所選項。

wdLine

5

一個線段。

wdParagraph

4

段落。

wdParagraphFormatting

14

段落格式。

wdRow

10

行。

wdScreen

7

屏幕尺寸。

wdSection

8

一節。

wdSentence

3

句子。

wdStory

6

部分。

wdTable

15

一個表格。

wdWindow

11

窗口。

wdWord

2

字。

2、WdBuiltinStyle枚舉類型說明

wdStyleBlockQuotation

-85

文本塊。

wdStyleBodyText

-67

正文文本。

wdStyleBodyText2

-81

正文文本 2。

wdStyleBodyText3

-82

正文文本 3。

wdStyleBodyTextFirstIndent

-78

正文首行縮進。

wdStyleBodyTextFirstIndent2

-79

正文首行縮進 2。

wdStyleBodyTextIndent

-68

正文文本縮進。

wdStyleBodyTextIndent2

-83

正文文本縮進 2。

wdStyleBodyTextIndent3

-84

正文文本縮進 3。

wdStyleBookTitle

-265

書籍標題。

wdStyleCaption

-35

題注。

wdStyleClosing

-64

結束語。

wdStyleCommentReference

-40

批注引用。

wdStyleCommentText

-31

批注文字。

wdStyleDate

-77

日期。

wdStyleDefaultParagraphFont

-66

默認段落字體。

wdStyleEmphasis

-89

強調。

wdStyleEndnoteReference

-43

尾注引用。

wdStyleEndnoteText

-44

尾注文本。

wdStyleEnvelopeAddress

-37

收信人地址。

wdStyleEnvelopeReturn

-38

寄信人地址。

wdStyleFooter

-33

頁腳。

wdStyleFootnoteReference

-39

腳注引用。

wdStyleFootnoteText

-30

腳注文本。

wdStyleHeader

-32

頁眉。

wdStyleHeading1

-2

標題 1。

wdStyleHeading2

-3

標題 2。

wdStyleHeading3

-4

標題 3。

wdStyleHeading4

-5

標題 4。

wdStyleHeading5

-6

標題 5。

wdStyleHeading6

-7

標題 6。

wdStyleHeading7

-8

標題 7。

wdStyleHeading8

-9

標題 8。

wdStyleHeading9

-10

標題 9。

wdStyleHtmlAcronym

-96

HTML 縮寫。

wdStyleHtmlAddress

-97

HTML 地址。

wdStyleHtmlCite

-98

HTML 引文。

wdStyleHtmlCode

-99

HTML 代碼。

wdStyleHtmlDfn

-100

HTML 定義。

wdStyleHtmlKbd

-101

HTML 鍵盤。

wdStyleHtmlNormal

-95

普通(網站)。

wdStyleHtmlPre

-102

HTML 預設格式。

wdStyleHtmlSamp

-103

HTML 樣本。

wdStyleHtmlTt

-104

HTML 打字機。

wdStyleHtmlVar

-105

HTML 變量。

wdStyleHyperlink

-86

超鏈接。

wdStyleHyperlinkFollowed

-87

訪問過的超鏈接。

wdStyleIndex1

-11

索引 1。

wdStyleIndex2

-12

索引 2。

wdStyleIndex3

-13

索引 3。

wdStyleIndex4

-14

索引 4。

wdStyleIndex5

-15

索引 5。

wdStyleIndex6

-16

索引 6。

wdStyleIndex7

-17

索引 7。

wdStyleIndex8

-18

索引 8。

wdStyleIndex9

-19

索引 9。

wdStyleIndexHeading

-34

索引標題。

wdStyleIntenseEmphasis

-262

明顯強調。

wdStyleIntenseQuote

-182

明顯引用。

wdStyleIntenseReference

-264

明顯參考。

wdStyleLineNumber

-41

行號。

wdStyleList

-48

列表。

wdStyleList2

-51

列表 2。

wdStyleList3

-52

列表 3。

wdStyleList4

-53

列表 4。

wdStyleList5

-54

列表 5。

wdStyleListBullet

-49

列表項目符號。

wdStyleListBullet2

-55

列表項目符號 2。

wdStyleListBullet3

-56

列表項目符號 3。

wdStyleListBullet4

-57

列表項目符號 4。

wdStyleListBullet5

-58

列表項目符號 5。

wdStyleListContinue

-69

列表接續。

wdStyleListContinue2

-70

列表接續 2。

wdStyleListContinue3

-71

列表接續 3。

wdStyleListContinue4

-72

列表接續 4。

wdStyleListContinue5

-73

列表接續 5。

wdStyleListNumber

-50

列表編號。

wdStyleListNumber2

-59

列表編號 2。

wdStyleListNumber3

-60

列表編號 3。

wdStyleListNumber4

-61

列表編號 4。

wdStyleListNumber5

-62

列表編號 5。

wdStyleListParagraph

-180

列出段落。

wdStyleMacroText

-46

宏文本。

wdStyleMessageHeader

-74

信息標題。

wdStyleNavPane

-90

文檔結構圖。

wdStyleNormal

-1

正文。

wdStyleNormalIndent

-29

正文縮進。

wdStyleNormalObject

-158

正文(應用於對象)。

wdStyleNormalTable

-106

正文(在表格中應用)。

wdStyleNoteHeading

-80

注釋標題。

wdStylePageNumber

-42

頁碼。

wdStylePlainText

-91

純文本。

wdStyleQuote

-181

引用。

wdStyleSalutation

-76

稱呼。

wdStyleSignature

-65

簽名。

wdStyleStrong

-88

要點。

wdStyleSubtitle

-75

副標題。

wdStyleSubtleEmphasis

-261

不明顯強調。

wdStyleSubtleReference

-263

不明顯參考。

wdStyleTableColorfulGrid

-172

彩色網格。

wdStyleTableColorfulList

-171

彩色列表。

wdStyleTableColorfulShading

-170

彩色底紋。

wdStyleTableDarkList

-169

深色列表。

wdStyleTableLightGrid

-161

淺色網格。

wdStyleTableLightGridAccent1

-175

淺色網格強調文字顏色 1。

wdStyleTableLightList

-160

淺色列表。

wdStyleTableLightListAccent1

-174

淺色列表強調文字顏色 1。

wdStyleTableLightShading

-159

淺色底紋。

wdStyleTableLightShadingAccent1

-173

淺色底紋強調文字顏色 1。

wdStyleTableMediumGrid1

-166

中間色網格 1。

wdStyleTableMediumGrid2

-167

中間色網格 2。

wdStyleTableMediumGrid3

-168

中間色網格 3。

wdStyleTableMediumList1

-164

中間色列表 1。

wdStyleTableMediumList1Accent1

-178

中間色列表 1 強調文字顏色 1。

wdStyleTableMediumList2

-165

中間色列表 2。

wdStyleTableMediumShading1

-162

中間色底紋 1。

wdStyleTableMediumShading1Accent1

-176

中間色底紋 1 強調文字顏色 1。

wdStyleTableMediumShading2

-163

中間色底紋 2。

wdStyleTableMediumShading2Accent1

-177

中間色底紋 2 強調文字顏色 1。

wdStyleTableOfAuthorities

-45

引文目錄。

wdStyleTableOfFigures

-36

圖表目錄。

wdStyleTitle

-63

標題。

wdStyleTOAHeading

-47

引文目錄標題。

wdStyleTOC1

-20

目錄 1。

wdStyleTOC2

-21

目錄 2。

wdStyleTOC3

-22

目錄 3。

wdStyleTOC4

-23

目錄 4。

wdStyleTOC5

-24

目錄 5。

wdStyleTOC6

-25

目錄 6。

wdStyleTOC7

-26

目錄 7。

wdStyleTOC8

-27

目錄 8。

wdStyleTOC9

-28

目錄 9。

3、_Application進程打開open()括號中的參數說明

表達式.打開 (FileName、ConfirmConversions、ReadOnly、AddToRecentFiles、PasswordDocument、PasswordTemplate、Revert、WritePasswordDocument、WritePasswordTemplate、Format、Encoding、Visible、OpenConflictDocument、OpenAndRepair、DocumentDirection、NoEncodingDialog)

 

名稱

必需/可選

數據類型

說明

FileName

必需

Variant

文檔名(可包含路徑)。

ConfirmConversions

可選

Variant

True 顯示 轉換文件 對話框中,如果該文件不是 Microsoft Word 格式。

ReadOnly

可選

Variant

 True,則以只讀方式打開文檔。 此參數不會覆蓋已保存文檔的只讀推薦設置。 例如,如果在打開只讀推薦設置的情況下保存文檔,則將 ReadOnly 參數設置為 False 將不會導致文件以讀/寫方式打開。

AddToRecentFiles

可選

Variant

 要將文件名添加到列表中最近使用的文件在 文件 菜單的底部。

PasswordDocument

可選

Variant

打開文檔時所需的密碼。

PasswordTemplate

可選

Variant

打開模板時所需的密碼。

Revert

可選

Variant

控制如果 FileName 是打開文檔的名稱會進行什么操作。 為 True,則放棄對打開文檔的任何未保存更改並重新打開文件。 為 False,則激活打開的文檔。

WritePasswordDocument

可選

Variant

用於保存文檔更改的密碼。

WritePasswordTemplate

可選

Variant

用於保存模板更改的密碼。

Format

可選

Variant

用於打開文檔的文件轉換器。 可為以下 WdOpenFormat 常量之一。 默認值為 wdOpenFormatAuto 若要指定外部文件格式,請將 OpenFormat 屬性應用於 FileConverter 對象,以確定要與此參數一起使用的值。

Encoding

可選

Variant

當你查看保存的文檔時 Microsoft Word 所使用的文檔編碼(代碼頁或字符集)。 可以是任何有效的 MsoEncoding 常量。 要查看有效 MsoEncoding 常量的列表,請參閱“Visual Basic 編輯器”中的“對象瀏覽器”。 默認值是系統代碼頁。

Visible

可選

Variant

如此 如果在可見窗口中打開文檔。 默認值為 True 。

OpenConflictDocument

可選

Variant

指定是否打開具有脫機沖突的文檔的沖突文件。

OpenAndRepair

可選

Variant

如果該屬性為 True ,則修復文檔,以防止文檔毀壞。

DocumentDirection

可選

WdDocumentDirection

表示文檔中的橫排文字。 默認值為 wdLeftToRight

NoEncodingDialog

可選

Variant

 True,如果無法識別文本編碼,則跳過顯示 Word 所顯示的“編碼”對話框。 默認值為 False

4、Selection.MoveDown()方法中參數說明

 

Unit

選用

WdUnits

選取范圍是要移動的單位。 默認值為 wdLine 。

Count

選用

Variant

移動選中項目的單位數。 默認值為 1。

Extend

選用

Variant

可以是 wdMove 或 wdExtend 如果使用 wdMove ,則選取范圍已折疊成結束點和向下移動。 如果使用 wdExtend 時,就會向下延伸選取項目。 默認值是 wdMove 。

 

5.Table表添加新表格

 

Add (Range NumRows NumColumns DefaultTableBehavior AutoFitBehavior)

Range

必要

Range object

要顯示表的范圍。如果范圍未折疊,則該表將替換該區域。

NumRows

必要

Long

要包括在表中的行數。

NumColumns

必要

Long

要包括在表中的列數。

DefaultTableBehavior

選用

Variant

設置一個值,該值指定 Microsoft Word 是否自動調整表中單元格的大小以適合單元格的內容 (AutoFit)。可以是以下常量之一:wdWord8TableBehavior(已禁用 AutoFit)或 wdWord9TableBehavior(已啟用 AutoFit)。默認常量為 wdWord8TableBehavior

AutoFitBehavior

選用

Variant

設置 Word 大小如何調整表格的自動調整規則。可以是 WdAutoFitBehavior 常量之一。

 

 

 

 

 

 

 

 

 

5.WdLineStyle枚舉說明

名稱

說明

wdLineStyleDashDot

5

划線后跟點。

wdLineStyleDashDotDot

6

划線后跟兩個點。

wdLineStyleDashDotStroked

20

划線后跟粗點,使邊框的外觀類似於理發店招牌。

wdLineStyleDashLargeGap

4

划線后跟大間隙。

wdLineStyleDashSmallGap

3

划線后跟小間隙。

wdLineStyleDot

2

點。

wdLineStyleDouble

7

雙實線。

wdLineStyleDoubleWavy

19

波浪型雙實線。

wdLineStyleEmboss3D

21

邊框看起來具有 3D 浮現外觀。

wdLineStyleEngrave3D

22

邊框看起來具有 3D 陰文外觀。

wdLineStyleInset

24

邊框呈現凹進效果。

wdLineStyleNone

0

無邊框。

wdLineStyleOutset

23

邊框呈現凸起效果。

wdLineStyleSingle

1

單實線

wdLineStyleSingleWavy

18

波浪型單實線。

wdLineStyleThickThinLargeGap

16

里面是一條粗實線,外面是一條細實線,兩條線的間隙較大。

wdLineStyleThickThinMedGap

13

里面是一條粗實線,外面是一條細實線,兩條線的間隙中等。

wdLineStyleThickThinSmallGap

10

里面是一條粗實線,外面是一條細實線,兩條線的間隙較小。

wdLineStyleThinThickLargeGap

15

里面是一條細實線,外面是一條粗實線,兩條線的間隙較大。

wdLineStyleThinThickMedGap

12

里面是一條細實線,外面是一條粗實線,兩條線的間隙中等。

wdLineStyleThinThickSmallGap

9

里面是一條細實線,外面是一條粗實線,兩條線的間隙較小。

wdLineStyleThinThickThinLargeGap

17

最里面是一條細實線,其次是一條粗實線,最外面是一條細實線,所有線之間的間隙較大。

wdLineStyleThinThickThinMedGap

14

最里面是一條細實線,其次是一條粗實線,最外面是一條細實線,所有線之間的間隙中等。

wdLineStyleThinThickThinSmallGap

11

最里面一條細實線,其次一條粗實線,最外面是一條細實線,所有線之間的間隙較小。

wdLineStyleTriple

8

三條細實線。

 

 

生成文檔效果圖

 

 

核心代碼:

using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ETWord
{
    public class WordHelper
    {
        public static void CreateWordFile(string filePath)
        {
            
            try
            {
                CreateFile(filePath);
                //
                MessageFilter.Register();
                object wdLine = WdUnits.wdLine;//一個線段
                object oMissing = Missing.Value;//表示這個參數可以傳入缺省值
                object fileName = filePath;
                object heading2 = WdBuiltinStyle.wdStyleHeading2;//標題一
                object heading3 = WdBuiltinStyle.wdStyleHeading3;//標題二
                
                _Application wordApp = new Application();//創建一個word進程
                wordApp.Visible = true;//word進程是否可見
                _Document wordDoc = wordApp.Documents.Open(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);//打開word進程
                System.Data.DataTable dtDepts = DatabaseHelper.getDept();//獲取大標題
                int ii = 0;
                foreach (DataRow dr in dtDepts.Rows)
                {
                    string dept = dr["dept"].ToString();//標題一
                    Paragraph oPara0 = wordDoc.Content.Paragraphs.Add(ref oMissing);//創建前三行表格
                    oPara0.Range.Text = string.Format("{0}-{1}", ii + 1, dept);//設置第二標題的序號
                    oPara0.Range.Select();
                    oPara0.set_Style(ref heading2);//設置樣式
                    oPara0.Range.InsertParagraphAfter();//在范圍之后插入段落標記
                    System.Data.DataTable dtTemplate = DatabaseHelper.getTemplateByDept(dept);//循環前三行
                    int jj = 0;
                    foreach (DataRow dr1 in dtTemplate.Rows)
                    {
                        string template = dr1["template"].ToString();//創建模板時設置的
                        string user1 = dr1["user1"].ToString();//創建模板時設置的
                        string remark = dr1["remark"].ToString();//創建模板時設置的
                        System.Data.DataTable dtData = DatabaseHelper.getDataByDeptAndTemplate(dept, template);//獲取數據
                        int count = dtData.Rows.Count;//獲取集合中總數量
                        int row = count + 4;//行數
                        int column = 5;
                        object ncount = 1;

                        wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);
                        wordApp.Selection.TypeParagraph();//插入一個新空白段落
                        Paragraph oPara1 = wordDoc.Content.Paragraphs.Add(ref oMissing);//創建第二個表格
                        oPara1.Range.Select();
                        oPara1.Range.Text = string.Format("{0}-{1}、{2}", ii + 1, jj + 1, template);//標題二
                        //oPara1.Range.Font.Bold = 1;
                        //oPara1.Format.SpaceAfter = 5;
                        oPara1.set_Style(ref heading3);//設置樣式
                        oPara1.Range.InsertParagraphAfter();//在范圍之后插入段落標記
                        wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);
                        wordApp.Selection.TypeParagraph();//插入一個新空白段落
                        //設置表格
                        Table table = wordDoc.Tables.Add(wordApp.Selection.Range, row, column, ref oMissing, ref oMissing);//創建新表格
                       
                        table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;//外邊框單實線
                        table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;//內邊框單實線
                        table.Range.Font.Bold = 0;//字體粗細
                        table.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthAuto;//設置表格寬度,基於當前所選內容自動選擇要使用的度量單位。
                        table.Columns[1].Width = 60f;
                        table.Columns[2].Width = 100f;
                        table.Columns[3].Width = 100f;
                        table.Columns[4].Width = 60f;
                        table.Columns[5].Width = 100f;
                        //列的合並
                        Cell cell = table.Cell(1, 2);
                        cell.Merge(table.Cell(1, 5));
                        Cell cell2 = table.Cell(2, 2);
                        cell2.Merge(table.Cell(2, 5));
                        Cell cell3 = table.Cell(3, 2);
                        cell3.Merge(table.Cell(3, 5));
                        //賦值
                        table.Cell(1, 1).Range.Text = "流程名稱:";
                        table.Cell(2, 1).Range.Text = "使用人:";
                        table.Cell(3, 1).Range.Text = "流程說明:";
                        table.Cell(4, 1).Range.Text = "節點";
                        table.Cell(4, 2).Range.Text = "節點名";
                        table.Cell(4, 3).Range.Text = "處理人員";
                        table.Cell(4, 4).Range.Text = "處理方式";
                        table.Cell(4, 5).Range.Text = "跳轉信息";
                        table.Cell(1, 2).Range.Text = template;//把值賦給第一行第二列表格
                        table.Cell(2, 2).Range.Text = user1;//把值賦給第二行第二列表格
                        table.Cell(3, 2).Range.Text = remark;//把值賦給第三行第二列表格
                        int kk = 5;
                        foreach (DataRow dr2 in dtData.Rows)
                        {
                            table.Cell(kk, 1).Range.Text = (kk - 4).ToString();
                            table.Cell(kk, 2).Range.Text = dr2["NodeName"].ToString();
                            table.Cell(kk, 3).Range.Text = dr2["DoName"].ToString();
                            table.Cell(kk, 4).Range.Text = dr2["DoType"].ToString();
                            table.Cell(kk, 5).Range.Text = string.Empty;
                            kk++;
                        }
                        table.Cell(kk - 1, 5).Range.Select();

                        wordApp.Selection.MoveDown(ref wdLine, ref ncount, ref oMissing);//移動焦點
                        wordApp.Selection.TypeParagraph();//插入段落

                        jj++;
                    }
                    ii++;
                }

                //保存文檔
                wordDoc.Save();
                wordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                wordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                MessageFilter.Revoke();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);

            }
        }

        private static void CreateFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                using (FileStream fs = File.Create(filePath))
                {

                }
            }
        }
    }
}
View Code

操作數據庫,模板的方法類:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ETWord
{
    public class DatabaseHelper
    {
        /// <summary>
        /// 獲取部門
        /// </summary>
        /// <returns></returns>
        public static DataTable getDept()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("dept");
            for (int i = 0; i < 5; i++)
            {
                DataRow dr = dt.NewRow();
                dr["dept"] = string.Format("部門_{0}_T", i + 1);
                dt.Rows.Add(dr);
            }
            return dt;
        }

        /// <summary>
        /// 獲取模板
        /// </summary>
        /// <param name="dept"></param>
        /// <returns></returns>
        public static DataTable getTemplateByDept(string dept)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("template");
            dt.Columns.Add("user1");
            dt.Columns.Add("remark");
            for (int i = 0; i < 5; i++)
            {
                DataRow dr = dt.NewRow();
                dr["template"] = string.Format("小組_{0}_A_{1}", i + 1,dept);
                dr["user1"] = string.Format("B_{0}_B_{1}", i + 1, dept);
                dr["remark"] = string.Format("C_{0}_C_{1}", i + 1, dept);
                dt.Rows.Add(dr);
            }
            return dt;
        }

        /// <summary>
        /// 獲取數據
        /// </summary>
        /// <param name="dept"></param>
        /// <param name="template"></param>
        /// <returns></returns>
        public static DataTable getDataByDeptAndTemplate(string dept, string template)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("NodeName");
            dt.Columns.Add("DoName");
            dt.Columns.Add("DoType");
            for (int i = 0; i < 5; i++)
            {
                DataRow dr = dt.NewRow();
                dr["NodeName"] = string.Format("AA_{0}_{1}", i,template);
                dr["DoName"] = string.Format("BB_{0}", i);
                dr["DoType"] = string.Format("CC_{0}",  i);
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ETWord
{
    public class MessageFilter : IOleMessageFilter
    {
        //
        // Class containing the IOleMessageFilter
        // thread error-handling functions.

        // Start the filter.
        public static void Register()
        {
            IOleMessageFilter newFilter = new MessageFilter();
            IOleMessageFilter oldFilter = null;
            CoRegisterMessageFilter(newFilter, out oldFilter);
        }

        // Done with the filter, close it.
        public static void Revoke()
        {
            IOleMessageFilter oldFilter = null;
            CoRegisterMessageFilter(null, out oldFilter);
        }

        //
        // IOleMessageFilter functions.
        // Handle incoming thread requests.
        int IOleMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo)
        {
            //Return the flag SERVERCALL_ISHANDLED.
            return 0;
        }

        // Thread call was rejected, so try again.
        int IOleMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
        {
            if (dwRejectType == 2)
            // flag = SERVERCALL_RETRYLATER.
            {
                // Retry the thread call immediately if return >=0 & 
                // <100.
                return 99;
            }
            // Too busy; cancel call.
            return -1;
        }

        int IOleMessageFilter.MessagePending(System.IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
        {
            //Return the flag PENDINGMSG_WAITDEFPROCESS.
            return 2;
        }

        // Implement the IOleMessageFilter interface.
        [DllImport("Ole32.dll")]
        private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter);
    }

    [ComImport(), Guid("00000016-0000-0000-C000-000000000046"),
    InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
    interface IOleMessageFilter
    {
        [PreserveSig]
        int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);

        [PreserveSig]
        int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);

        [PreserveSig]
        int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
    }
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM