I am well stuck,
How do you determine if a word document is already open within VB.NET?
I would be grateful of any help.
Thanks.
Printable View
I am well stuck,
How do you determine if a word document is already open within VB.NET?
I would be grateful of any help.
Thanks.
Is it Word instance or the actual document?
Do you want to check only based on the file name?
The following dll and the code might help you, but it is not a good way, because you might have two files with same name but form different locations and you can't say which is open using this method.
VB Code:
Dim main As Win32Util.Win32Window Dim id As IntPtr Dim proc() As Process = Process.GetProcessesByName("winword") MessageBox.Show(proc.Length) If proc.Length > 0 Then id = proc(0).Handle main = New Win32Util.Win32Window(id) If main.FindWindow(Nothing, "My file - Microsoft Word").IsNull Then MessageBox.Show("Not Found!") Else MessageBox.Show("Found!") End If Else MessageBox.Show("Winword is not running at all!") End If
You may also try opening the document in word and if it is open it will through an error, but if not, it will open and I guess that's not what you desire.
Thanks for your replies.
What I am trying to do is to check to see if the user has a word document open. I am writing a report out using a word template (located on the local disk) and subsequently saving the document (to a network area) using variables that are unique to the customer.
Firstly, I need to check to see if the word template is not open. If the template is open then I will produce an error message telling the user that they must close the template before proceeding and exit out of subroutine with no further processing.
Secondly, I need to check to see if the file I am saving is not open. I'm not bothered if the file exists as the users of the system are quite happy to have the file overwritten, but the file cannot be exclusively assigned to another user.
I am currently having a look at checking for temporary word files open in the directory to ascertain whether a certain document is open or not. However, I will try the dll posted. Thanks once again for your help.
Got it.
When a word document is opened, a temporary file is created with a prefix of ~$. However, if the file name is over a certain length (4 or 5 chars I think). In order to get around this problem, I prefix the file that I am saving with 2 underscores (i.e. __MyWordDocument.doc).
When __MyWordDocument.doc is open, it's temporary file ~$MyWordDocument.doc exists in the same directory. In order to check that it exists, I wrote the following code in my subroutine
This stops any attempts to open an already open word document.Code:If File.Exists(Application.StartupPath & "\~$MyWordDocument.doc") Then
MsgBox("File already being edited. Please close this file before trying again")
Exit Sub
End If
Thanks once again for your help.