如何仅在代码[C#]中创建AxHost

时间:2008-09-19 22:15:29

标签: c# activex ocx

我正在使用COM Wrapper与Windows Media Player进行交互。

它正在使用AxHost以某种方式包裹玩家,对我而言,它只是引擎盖下的魔法^^

AxHost.AttachInterfaces看起来像这样

    protected override void AttachInterfaces() 
    {
        try 
        {   
            //Get the IOleObject for Windows Media Player.
            IOleObject oleObject = this.GetOcx() as IOleObject;

            //Set the Client Site for the WMP control.
            oleObject.SetClientSite(this as IOleClientSite);

            Player = this.GetOcx() as WMPLib.WindowsMediaPlayer; 
...

只要我在Windows窗体控件中托管此AxHost,一切正常。但我无法在构造函数中挂接事件。

例如,这不起作用:

    public WMPMediaRating()
    {
        var remote = new WMPRemote.RemotedWindowsMediaPlayer();
        _WMP = remote.Player;

        _WMP.MediaChange += new _WMPOCXEvents_MediaChangeEventHandler(_WMP_MediaChange);
    }

remote.Player始终为null,程序因NullReferencesException崩溃。

AttachInterfaces()中的代码以某种方式仅在绘制Form之后执行,或者在完成其他所有操作之后执行。

我尝试手动调用AttachInterfaces(),但由于GetOcx()没有返回任何内容,因此无效。


那么如何在没有Windows Forms的情况下实例化我的AxHost继承控件,以便在控制台应用程序中使用它?

1 个答案:

答案 0 :(得分:1)

仅供参考:没有人阻止您在控制台应用程序中使用隐藏窗口。

您将无法在非Windows应用程序中托管媒体播放器 - 它需要托管。如果你想播放一些音乐,你可以使用媒体图来创建一个呈现(播放)你的音乐文件的图形 - 它不需要任何额外的托管。