简体   繁体   中英

How to prevent SaveAs dialog in Word in C#?

I am developing a custom ribbon in Microsoft Word document. I intend to override the save functionality by disabling it and save the document programmatically.

I have added DocumentBeforeSave event Handler to save the document. Here is the part of the code to save the document

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{

    Globals.ThisAddIn.Application.DocumentBeforeSave += new Word.ApplicationEvents4_DocumentBeforeSaveEventHandler(this.Application_DocumentBeforeSave);
}

public void Application_DocumentBeforeSave(Word.Document document, ref bool saveAsUI, ref bool cancel)            
{
    String destFolder = @"D:\report\tempFolder\";
    Random rnd = new Random();
    String fileName = "Temp_" + rnd.Next(1000, 9999).ToString() + ".docx";
    var destFile = System.IO.Path.Combine(destFolder, fileName);

    document.SaveAs2(destFile);
}

Any idea how to do that?

Be aware, you are trying to save the document by calling the SaveAs2 method in the DocumentBeforeSave event handler. Calling the SaveAs2 method triggers the DocumentBeforeSave method, so you will get a recursion and your dialog will never be displayed.

How to prevent SaveAs dialog in Word in C#?

In the DocumentBeforeSave event handler you may set up the saveAsUI parameter which is true if the Save As dialog box is displayed, whether to save a new document, in response to the Save command; or in response to the Save As command; or in response to the SaveAs or SaveAs2 method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM