Hi alpha,
i need to develop a short stand alone solution, that starts word if it
isn't started.
Glad to see you found your way here. By "stand alone solution" I'm going
to assume a Windows form, but what I show you is also applicable to a
Console application.
I've taken the sample code from a test application I use for various
scenarios, so you probably won't need all the "using" statements listed.
You definitely need the last two and the VS IDE should generate them when
you set a reference to the Word object model library. Of primary
importance for you is the GetWordInstance method that demonstrates how
you can determine if a Word *process* is running and pick it up. If none
is running, then a new instance is started. This application loads it
into a global variable, but you could easily change the method to return
the Word Application, instead, if that would be more appropriate for your
requirement.
Using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using wd = Microsoft.Office.Interop.Word;
using office = Microsoft.Office.Core;
namespace WinForm_OfficeAutomation
{
public partial class Form1 : Form
{
wd.Application wdApp;
System.Diagnostics.Process pcs;
object missing = System.Reflection.Missing.Value;
object objTrue = true;
object objFalse = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
wd.Document wdDoc;
if (GetWordInstance())
{
try
{
wdApp.Visible = true;
wdDoc = wdApp.Documents.Add(ref missing, ref missing,
ref missing, ref objTrue);
CreateWaterMark(wdDoc);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private bool GetWordInstance()
{
bool retVal = false;
try
{
System.Diagnostics.Process[] wdPcs=
System.Diagnostics.Process.GetProcessesByName("WinWord");
if (wdPcs.Length > 0)
{
pcs = wdPcs[0];
wdApp =(wd.Application)
System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application"
);
}
else
{
wdApp = new wd.Application();
}
if (wdApp != null) retVal = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return retVal;
}
Cindy Meister
INTER-Solutions, Switzerland
http://homepage.swissonline.ch/cindymeister (last update Jun 17 2005)
http://www.word.mvps.org
This reply is posted in the Newsgroup; please post any follow question or
reply in the newsgroup and not by e-mail