簡體   English   中英

UserControl不包含針對應用程序的定義

[英]UserControl does not contain a defination for Application

我試圖在單擊按鈕時在活動Word文檔中執行搜索操作。 而且在我的代碼中出現錯誤是

該按鈕位於自定義任務窗格上

錯誤CS1061'UserControl1'不包含'Application'的定義,找不到可以接受的擴展方法'Application'接受類型為'UserControl1'的第一個參數(您是否缺少using指令或程序集引用?)WordAddIn1 c: \\ users \\ veroot \\ source \\ repos \\ WordAddIn1 \\ WordAddIn1 \\ UserControl1.cs 29有效

代碼是

private void button1_Click(object sender, EventArgs e)
    {
        object findText = textBox1.Text;
        object missing = System.Type.Missing;

        Word.Document document = this.Application.ActiveDocument;
        Word.Range rng = document.Range(0, Type.Missing);


        rng.Find.Highlight = 0;
        rng.Find.Forward = true;
        do
        {
            if (rng.HighlightColorIndex == WdColorIndex.wdYellow)
            {

                rng.HighlightColorIndex = WdColorIndex.wdRed;
                rng.Font.ColorIndex = WdColorIndex.wdBlue;
            }
            int intPosition = rng.End;
            rng.Start = intPosition;
        } while (rng.Find.Execute("", missing, missing, missing, missing, missing, true,
            missing, missing, missing, missing, missing, missing, missing, missing));
    }

在VSTO解決方案中,只能使用關鍵字this引用ThisAddin類中的宿主Office應用程序。 在所有其他類(包括用於UserControl的類)中, this將引用該類(UserControl),並且與宿主Office應用程序沒有任何關系或連接。 因此,對於問題中顯示的代碼, this是指UserControl類。

為了引用運行VSTO加載項的Office應用程序,最好使用Globals關鍵字。 例如

 Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;

要么

 Word.Document doc = Globals.ThisAddIn.app.ActiveDocument;

其中appThisAddin類中的類級字段-示例聲明:

    public partial class ThisAddIn
    {
        public Word.Application app;

ThisAddin_Startup分配的-例如:

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        app = this.Application;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM