Intercept Save event in Word 'Save As' dialog

佐手、 提交于 2019-12-11 08:49:24

问题


In Word, I have an open document - I navigate in the 'Save As' dialog to a directory and select an existing file. When I now click 'Save' instead of 'Cancel', I get the message if I want to overwrite/merge the existing document.

Is it possible to intercept the 'Save' event in the 'Save As' Dialog so that I can change the file name of the open document, suppressing the overwrite/merge message? Any suggestions are greatly appreciated!


回答1:


Yes, it is totally possible to intercept Word commands. In the VBA days, it was as easy as creating a macro with the same name as the internal Word command.

In VSTO, you need to add the command overwrite to your Ribbon XML and then add a callback to your code.

The entire procedure is described in MSDN: Temporarily Repurpose Commands on the Office Fluent Ribbon

Sample Ribbon XML (overwriting the standard Save command)

<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" 
   onLoad="OnLoad" > 
   <commands> 
     <command idMso="FileSave" onAction="mySave" /> 
   </commands> 
   <ribbon startFromScratch="false"> 
     <tabs> 
       <tab id="tab1" label="Repurpose Command Demo" > 
         <group id="group1" label="Demo Group"> 
           <toggleButton id="togglebutton1"  
             imageMso="AcceptInvitation"  
             size="large"  
             label="Alter Built-ins"  
             onAction="changeRepurpose" /> 
         </group> 
       </tab> 
     </tabs> 
   </ribbon> 
</customUI>

Ribbon Callback

public void mySave(IRibbonControl control, bool cancelDefault)
{
    MessageBox.Show("The Save button has been temporarily repurposed.");
    cancelDefault = false;
}



回答2:


You can replace the Office dialog by your own like this

https://msdn.microsoft.com/en-us/library/sfezx97z(v=vs.110).aspx

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    Globals.ThisAddIn.Application.DocumentBeforeSave += Application_DocumentBeforeSave;

}    

void Application_DocumentBeforeSave(Word.Document Doc, ref bool SaveAsUI, ref bool Cancel)
{
    SaveFileDialog dgSave = new SaveFileDialog();
    dgSave.Title = "This is my save dialog";
    dgSave.FileName = "This is the initial name";
    dgSave.InitialDirectory = "C:\\Temp";
    dgSave.FileOk += dgSave_FileOk;
    DialogResult result = dgSave.ShowDialog();
}

void dgSave_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
    var test = (SaveFileDialog)sender;
    MessageBox.Show("You clicked on SAVE and this file is selected " + test.FileName);
}

Note: usually you will work with the result and then doing your action rather than catching the FileOk event but it sounds like in this case you want to do that



来源:https://stackoverflow.com/questions/39159944/intercept-save-event-in-word-save-as-dialog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!