Welcome to Vikram's JAVA to COM page
It took my precious time to launch COM objects from pure JAVA.The purpose of this page is that you fellow programmers don't have to waste that much time.Here is some sample code to launch MS Word and open a new document from java application.The sample java class "myclass" calls "launch" method of native dll.
I assume you know how to use JNI to call a native method.If not , you can consult any good java book.
Java application code:
//*********start of java code*******************************
public class myclass {
static {
System.loadLibrary("myDLL");
}
public native String launch(String txt);
public static void main(String args[])
{
String s;
s=launch("My first document from java");
System.out.println("s");
}
}
//************end of java code**********************
VC++ Code:
The following code has been written using VC++6.0 .It is a non MFC console dll.Before compiling following
code be sure to add the path of "import" files to Tools>>Options>>Directories in VC++ IDE.
//************start of VC++ DLL code*******************
#import<mso97.dll>
#import<vbeext1.olb>
#import
<msword8.olb>
#include<tchar.h>
#include<myclass.h>
void dump_com_error(_com_error &e)
{
_tprintf(_T("An error occured!\n"));
_tprintf(_T("\a\tCode = %08lx\n"), e.Error());
_tprintf(_T("\a\tCode meaning = %s\n"), e.ErrorMessage());
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
_tprintf(_T("\a\tSource = %s\n"), (LPCTSTR) bstrSource);
_tprintf(_T("\a\tDescription = %s\n"), (LPCTSTR) bstrDescription);
}
struct StartOle
{
StartOle() { CoInitialize(NULL); }
~StartOle() { CoUninitialize();}
} _inst_StartOle;
JNIEXPORT jstring JNICALL Java_myclass_launch (JNIEnv *env, jobject obj, jstring txt)
{
const char *txt2=env->GetStringUTFChars(txt,0);
using namespace Word;
try {
_ApplicationPtr app;
app.CreateInstance(L"word.application.8");
app->put_Visible(VARIANT_TRUE);
_DocumentPtr doc;
doc=app->Documents->Add();
doc->Activate();
doc->ActiveWindow->WindowState=wdWindowStateMaximize;
RangePtr r;
r=doc->Range();
r->PutText(txt2);
} catch(_com_error &e) { dump_com_error(e);}
char *p="ok";
return env->NewStringUTF(p);
}
//*************end of VC++ DLL code*******************
I hope it helps.
This page has been
visited
times since
23Dec,1999.
If you have any suggestions,queries or comments, please feel free to let me know.
Related links:
Member Of The Open Source Java Web-Ring |
---|
[Skip Prev] [Prev] [Next] [Skip Next] [Random] [Next 5] [List Sites] |