c# - New instance of Word acts as a child process to existing hosted Word application -


i working on word automation tool, host word in wpf window. use following code create new word application

    // initialize handle value invalid     appwin = intptr.zero;      // start remote application     try         {             // start process             if (_wordapp == null) _wordapp = new applicationclass();             _wordapp.application.caption = word_app_name;              //find process             appwin = findwindow("opusapp", _wordapp.application.caption);         }         catch (exception ex)         {             messagebox.show(this, ex.message, "error");         }                     // put form         setparent(appwin, this.handle); 

on closing application want spawned word apps killed.

    protected override void onhandledestroyed(eventargs e)     {         // stop application         if (appwin != intptr.zero)         {             // sure word app closes without trace              try             {                 uint pid;                 uint pid2 = getwindowthreadprocessid(appwin,out pid);                  process proc = process.getprocessbyid((int)pid);                 proc.kill();             }             catch (exception)             {                 //write logs.             }             _wordapp = null;              // clear internal handle             appwin = intptr.zero;         }         base.onhandledestroyed (e);     } 

the problem when user uses application , opens new word document in parallel, new word acts child process of present process, hence on killing process new word app closed well.

how can make sure word app use different process other word application running or opened later.

you don't need kill process. it's enough keep reference word application create , call quit method.

for example:

[dllimport("user32.dll", setlasterror = true)] static extern intptr setparent(intptr hwndchild, intptr hwndnewparent);  microsoft.office.interop.word.application word;  private void button1_click(object sender, eventargs e) {     word = new microsoft.office.interop.word.application();     var documents = word.documents;     documents.open(@"d:\file1.docx");     setparent(new intptr(word.activewindow.hwnd), this.handle);     word.visible = true; } private void form1_formclosing(object sender, formclosingeventargs e) {     if (word != null)         word.quit(); } 

Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -