PDA

View Full Version : [SOLVED:] Stop Deletion of a Content Control during the Before Delete event



rruckus
03-12-2015, 02:35 PM
I have a Content Control in my Word document that I want to make sure no one deletes. I was hoping to use the "Document_ContentControlBeforeDelete" event to check the tag name and then stop the delete based on the name of the tag, but I don't see a way to stop the delete. Usually there would be a "Cancel" option or similar. Trying to "Undo" within that function doesn't work. "Undo" could be set on an "application.run" or timer to move it later in the stack but that's really a hack, because someone could then "redo". Does anyone know how to do this? Or is there another way?

I can't rely on the CC "Locked" property because users could always change the lock and then delete it - among other reasons.

Any ideas?

gmaxey
03-12-2015, 04:57 PM
The only reasonable thing I can suggest is to apply editing restrictions to the document (No changes, read only) and make the CCs editable regions.

UserName500
06-22-2017, 02:18 AM
Hello.

I'm trying to cancel the deletion of a content control with the event "Document_ContentControlBeforeDelete" using C# in Visual Studio 2015.

But I could not find out yet. So far I managed to recreate the same content control, when it gets deleted:


private void ActiveDocument_ContentControlBeforeDelete(Word.ContentControl OldContentControl, bool InUndoRedo) {

string oldTag = OldContentControl.Tag;
string oldTitle = OldContentControl.Title;
string oldText = OldContentControl.Range.Text;


reCreateCC(oldTag, oldTitle, oldText);


}


private void reCreateCC(string oldTag, string oldTitle, string oldText) {

RichTextContentControl ReechText = vstoDocument.Controls.AddRichTextContentControl("CC_" + System.Convert.ToString(++index));


ReechText.Tag = oldTag;
ReechText.Title = oldTitle;
ReechText.Range.Text = oldText;

}


But this is for sure not the best solution and it's very buggy. Does anyone know how to cancel the deletion in a proper way?

UserName500
08-03-2017, 05:03 AM
I have come across a solution that solved my problem. I just registered an event, when the Selection changes, Word checks if a content control is present in that selection. IF there is a content control, the selection is set to 0. So the user can't select a content control to delete it.


vstoDocument = Globals.Factory.GetVstoObject(this.Application.ActiveDocument);


vstoDocument.SelectionChange += VstoDocument_SelectionChange;


private void VstoDocument_SelectionChange(object sender, SelectionEventArgs e) {

Word.Selection selection = this.Application.Selection;

foreach (Word.ContentControl c in selection.ContentControls)
{

if(c != null)
{
selection.SetRange(0, 0);
MessageBox.Show("Content Controls not selectable!");
}

}



}

You can thank me later :cool: