[Microsoft代理程式從 Windows 7 開始已被取代,而且可能無法在後續版本的 Windows 中使用。]
您也可以從 Java 小程式存取 Microsoft Agent 服務。 許多可透過 Microsoft Agent 介面存取的函式會透過以參考方式傳遞的參數來傳回值。 若要從 Java 傳遞這些參數,您必須在程式代碼中建立單一元素陣列,並將其當做參數傳遞至適當的函式。 如果您使用 Microsoft Visual J++ 並在 Microsoft Agent 伺服器上執行 Java 類型庫精靈,請參閱 summary.txt 檔案,以檢閱哪些函式需要數位自變數。 此程式與 C 中的程序類似;您可以使用 IAgentEx 介面來建立伺服器的實體,然後載入字元:
private IAgentEx m_AgentEx = null;
private IAgentCharacterEx m_Merlin[] = {null};
private int m_MerlinID[] = {-1};
private int m_RequestID[] = {0};
private final String m_CharacterPath = "merlin.acs";
public void start()
{
// Start the Microsoft Agent Server
m_AgentEx = (IAgentEx) new AgentServer();
try
{
Variant characterPath = new Variant();
characterPath.putString(m_CharacterPath);
// Load the character
m_AgentEx.Load(characterPath,
m_MerlinID,
m_RequestID);
}
當從 HTTP 遠端位置(如網站)載入字元時,過程會稍有不同。 在此情況下,Load 方法是異步的,而且會引發 COM 例外狀況 E_PENDING (0x8000000a)。 您需要捕捉此例外並正確處理,如以下函式所示:
// Constants used in asynchronous character loads
private final int E_PENDING = 0x8000000a;
private final int NOERROR = 0;
// This function loads a character from the specified path.
// It correctly handles the loading of characters from
// remote sites.
// This sample doesn't care about the request id returned
// from the Load call. Real production code might use the
// request id and the RequestComplete callback to check for
// a successful character load before proceeding.
public int LoadCharacter(Variant path, int[] id)
{
int requestid[] = {-1};
int hRes = 0;
try
{
// Load the character
m_AgentEx.Load(path, id, requestid);
}
catch(com.ms.com.ComException e)
{
// Get the HRESULT
hRes = e.getHResult();
// If the error code is E_PENDING, we return NOERROR
if (hRes == E_PENDING)
hRes = NOERROR;
}
return hRes;
}
public void start()
{
if (LoadCharacter(characterPath, m_MerlinID) != NOERROR)
{
stop();
return;
}
// Other initialization code here
.
.
.
}
然後取得 IAgentCharacterEx 介面,可讓您存取其方法:
// Get the IAgentCharacterEx interface for the loaded
// character by passing its ID to the Agent server.
m_AgentEx.GetCharacterEx(m_MerlinID[0], m_Merlin);
// Show the character
m_Merlin[0].Show(FALSE, m_RequestID);
// And speak hello
m_Merlin[0].Speak("Hello World!", "", m_RequestID);
同樣地,若要收到事件的通知,您必須實作 IAgentNotifySink 或 IAgentNotifySinkEx 介面,並建立並註冊該類型的物件:
...
// Declare an Agent Notify Sink so that we can get
// notification callbacks from the Agent server.
private AgentNotifySinkEx m_SinkEx = null;
private int m_SinkID[] = {-1};
public void start()
{
...
// Create and register a notify sink
m_SinkEx = new AgentNotifySinkEx();
m_AgentEx.Register(m_SinkEx, m_SinkID);
…
// Give our notify sink access to the character
m_SinkEx.SetCharacter(m_Merlin[0]);
...
}
若要從 Java Applet 存取 Microsoft Agent,您必須產生使用 applet 安裝的 Java 類別。 例如,您可以使用 Visual J++ Java 類型庫精靈來產生這些檔案。 如果您打算在網頁上裝載小程式,則必須建置已簽署的 Java CAB,其中包含隨頁面下載的已產生類別檔案。 類別檔案是存取 Microsoft Agent Server 的必需項目,因為它是在 Java 沙盒外部執行的 COM 物件。