【问题标题】:How to know if word document opened by form is successfully opened in c#c#如何知道表单打开的word文档是否成功打开
【发布时间】:2015-09-11 21:45:08
【问题描述】:

背景: 我正在创建应用程序来捕获屏幕并将屏幕截图粘贴到另一个下方的 word 文档中。

技术部分: 当我运行该应用程序时,会打开一个 Word 文档以及一个带有“捕获”按钮的表单。单击该按钮会捕获屏幕并打开一个窗口询问标题,然后将带有标题的屏幕截图粘贴到当前打开的 Word 文档中。

我的问题 当用户点击捕获按钮时,我想检查之前打开的文档是否仍然打开。如果文档没有打开,我会提示用户打开一个新的空白文档。

我搜索了许多论坛和互联网,但大多数人都建议从当前运行的进程中获取文件名。 请注意,我的 word 文档未保存,因此它的名称会像“文档 1”等,这将是一种不好的检查方式。

我在下面粘贴了我的代码以供参考。

我们将不胜感激。提前致谢。

WordProcessing.cs

namespace WordProcessing
{
    class MSWord
    {
        Word.Application wordApp = new Word.Application();   //Creates new Word Instance

        public MSWord()
        {
            wordApp.Visible = true;
            Word.Document oDoc = wordApp.Documents.Add(ref useDefaultValue, ref useDefaultValue, ref useDefaultValue, ref useDefaultValue);
        }
   }
}

截屏.cs

namespace Screencapture
{
    public partial class form_capture : Form
    {
        MSWord word = new MSWord();

        public void button1_Click(object sender, EventArgs e)
        {
           /* Here I want to check whether document opened by 'word' object is still open */

            ScreenCapture screen = new ScreenCapture();
            screen.CaptureScreenToFile("D:/image.png", System.Drawing.Imaging.ImageFormat.Png);

            //Form to ask for caption
            DataForm textarea = new DataForm();
            textarea.ShowDialog();
            textarea.Focus();

            word.InsertText(DataForm.textarea_text);
            word.InsertImage(@"D:\image.png");

        }
    }
}

PS:忽略任何语法错误或缺少的函数定义。为了更好地理解,我粘贴了较短的版本。

【问题讨论】:

标签: c# .net screenshot office-interop


【解决方案1】:

尝试/捕捉文档的焦点如何?

try
{
    oDoc.Activate();
    //or on the application
    wordApp.Activate();
}
catch
{
  //Open a new document or ask
  Messagebox.Show("Please open a new Word Document");
}

【讨论】:

    【解决方案2】:

    您可以尝试使用File.Open() 方法。如果文档是打开的,它应该为您提供一个可以打印您的自定义提示的异常:

      FileStream stream = null;
        bool isOpen = false;
        try
        {
           stream = File.Open(@"DFilePath&Name",FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch(IOException)
        {
          isOpen = true;
          //Show your prompt here.
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }
        if(!isOpen)    
          Process.Start(@"FilePath&Name");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多