使用C#从WMP检索歌曲名称

使用C#我试图检索当前正在播放的歌曲的名称并将其显示在listBox上,因此播放的每首歌曲都显示在列表框中。

Using System; Using WMPLib; public IWMPMedia currentMedia { get; set; } private void button1_Click(object sender, EventArgs e) { Player = new WMPLib.WindowsMediaPlayer(); string song = Player.currentMedia.name.ToString(); listBox1.Items.Add(song); } 

但它抛出了我的例外。 “对象引用未设置为对象的实例”此处:

  string song = Player.currentMedia.name.ToString(); 

有谁知道如何解决这个问题?

您将不得不使用COM / OLE来执行此操作。 我做了一个类似于前一段时间的程序,不幸的是,我找不到我的客户端代码,但我仍然拥有为WMPLib实现IOleClientSite / IOleServiceProvider的代码。

我在以下url找到了代码: http : //sirayuki.sakura.ne.jp/WmpSample/WmpRemote.zip

它的一些代码是由微软员工Jonathan Dibble撰写的,如果我没记错的话。 Zip中有一个CHM,每个类都有一些解释。

inheritance了我仍然拥有的代码,以防链接断开,但就像我说我找不到使用它的代码。 它几乎正确地工作但我记得剩下的一个错误是它会在媒体播放器和我的应用程序关闭后留下wmplayer.exe进程。

更新
发现了一些客户端代码和RemotedWindowsMediaPlayer.cs的简单修改版本

我刚刚发现了一些我测试过的编码,它可以工作。 它来自Winform项目,你需要引用WMPLib来实现它。

在我的表单中,我添加了一个按钮和此代码:

  ///  /// Default Constructor ///  RemotedWindowsMediaPlayer rm; public FrmMain() { // // Required for Windows Form Designer support // InitializeComponent(); //Call me old fashioned - I like to do this stuff manually. You can do a drag //drop if you like, it won't change the results. rm = new RemotedWindowsMediaPlayer(); rm.Dock = System.Windows.Forms.DockStyle.Top; panel1.Controls.Add(rm); return; } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(((WMPLib.IWMPPlayer4)rm.GetOcx()).currentMedia.sourceURL); } 

RemotedWindowsMediaPLayer.cs:

 namespace RemoteWMP { using System; using System.Windows.Forms; using System.Runtime.InteropServices; using WMPLib; ///  /// This is the actual Windows Media Control. ///  [System.Windows.Forms.AxHost.ClsidAttribute("{6bf52a52-394a-11d3-b153-00c04f79faa6}")] [ComVisible(true)] [ClassInterface(ClassInterfaceType.AutoDispatch)] public class RemotedWindowsMediaPlayer : System.Windows.Forms.AxHost, IOleServiceProvider, IOleClientSite { ///  /// Used to attach the appropriate interface to Windows Media Player. /// In here, we call SetClientSite on the WMP Control, passing it /// the dotNet container (this instance.) ///  protected override void AttachInterfaces() { try { //Get the IOleObject for Windows Media Player. IOleObject oleObject = this.GetOcx() as IOleObject; if (oleObject != null) { //Set the Client Site for the WMP control. oleObject.SetClientSite(this as IOleClientSite); // Try and get the OCX as a WMP player if (this.GetOcx() as IWMPPlayer4 == null) { throw new Exception(string.Format("OCX is not an IWMPPlayer4! GetType returns '{0}'", this.GetOcx().GetType())); } } else { throw new Exception("Failed to get WMP OCX as an IOleObject?!"); } return; } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } } #region IOleServiceProvider Memebers - Working ///  /// During SetClientSite, WMP calls this function to get the pointer to . ///  /// See MSDN for more information - we do not use this parameter. /// The Guid of the desired service to be returned. For this application it will always match /// the Guid of . ///  IntPtr IOleServiceProvider.QueryService(ref Guid guidService, ref Guid riid) { //If we get to here, it means Media Player is requesting our IWMPRemoteMediaServices interface if (riid == new Guid("cbb92747-741f-44fe-ab5b-f1a48f3b2a59")) { IWMPRemoteMediaServices iwmp = new RemoteHostInfo(); return Marshal.GetComInterfaceForObject(iwmp, typeof(IWMPRemoteMediaServices)); } throw new System.Runtime.InteropServices.COMException("No Interface", (int) HResults.E_NOINTERFACE); } #endregion #region IOleClientSite Members ///  /// Not in use. See MSDN for details. ///  /// E_NOTIMPL void IOleClientSite.SaveObject() { throw new System.Runtime.InteropServices.COMException("Not Implemented", (int) HResults.E_NOTIMPL); } ///  /// Not in use. See MSDN for details. ///  ///  object IOleClientSite.GetMoniker(uint dwAssign, uint dwWhichMoniker) { throw new System.Runtime.InteropServices.COMException("Not Implemented", (int) HResults.E_NOTIMPL); } ///  /// Not in use. See MSDN for details. ///  ///  object IOleClientSite.GetContainer() { return (int)HResults.E_NOINTERFACE; } ///  /// Not in use. See MSDN for details. ///  ///  void IOleClientSite.ShowObject() { throw new System.Runtime.InteropServices.COMException("Not Implemented", (int) HResults.E_NOTIMPL); } ///  /// Not in use. See MSDN for details. ///  ///  void IOleClientSite.OnShowWindow(bool fShow) { throw new System.Runtime.InteropServices.COMException("Not Implemented", (int) HResults.E_NOTIMPL); } ///  /// Not in use. See MSDN for details. ///  ///  void IOleClientSite.RequestNewObjectLayout() { throw new System.Runtime.InteropServices.COMException("Not Implemented", (int) HResults.E_NOTIMPL); } #endregion ///  /// Default Constructor. ///  public RemotedWindowsMediaPlayer() : base("6bf52a52-394a-11d3-b153-00c04f79faa6") { } } } 

RemoteHostInfo.cs

 using System; namespace RemoteWMP { using System.Runtime.InteropServices; ///  /// This class contains the information to return to Media Player about our remote service. ///  [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] public class RemoteHostInfo : IWMPRemoteMediaServices { #region IWMPRemoteMediaServices Members ///  /// Returns "Remote" to tell media player that we want to remote the WMP application. ///  ///  public string GetServiceType() { return "Remote"; } ///  /// The Application Name to show in Windows Media Player switch to menu ///  ///  public string GetApplicationName() { return System.Diagnostics.Process.GetCurrentProcess().ProcessName; } ///  /// Not in use, see MSDN for more info. ///  ///  ///  ///  public HResults GetScriptableObject(out string name, out object dispatch) { name = null; dispatch = null; //return (int) HResults.S_OK;//NotImplemented return HResults.E_NOTIMPL; } ///  /// For skins, not in use, see MSDN for more info. ///  ///  ///  public HResults GetCustomUIMode(out string file) { file = null; return HResults.E_NOTIMPL;//NotImplemented } #endregion } } 

COM Interfaces.cs

 using System; namespace RemoteWMP { using System.Runtime.InteropServices; #region Useful COM Enums ///  /// Represents a collection of frequently used HRESULT values. /// You may add more HRESULT VALUES, I've only included the ones used /// in this project. ///  public enum HResults { ///  /// HRESULT S_OK ///  S_OK = unchecked((int)0x00000000), ///  /// HRESULT S_FALSE ///  S_FALSE = unchecked((int)0x00000001), ///  /// HRESULT E_NOINTERFACE ///  E_NOINTERFACE = unchecked((int)0x80004002), ///  /// HRESULT E_NOTIMPL ///  E_NOTIMPL = unchecked((int)0x80004001), ///  /// USED CLICKED CANCEL AT SAVE PROMPT ///  OLE_E_PROMPTSAVECANCELLED = unchecked((int)0x8004000C), } ///  /// Enumeration for  ///  public enum DVASPECT { ///  /// See MSDN for more information. ///  Content = 1, ///  /// See MSDN for more information. ///  Thumbnail = 2, ///  /// See MSDN for more information. ///  Icon = 3, ///  /// See MSDN for more information. ///  DocPrint = 4 } ///  /// Emumeration for  ///  public enum TAGOLECLOSE :uint{ OLECLOSE_SAVEIFDIRTY = unchecked((int)0), OLECLOSE_NOSAVE = unchecked((int)1), OLECLOSE_PROMPTSAVE = unchecked((int)2) } #endregion #region IWMPRemoteMediaServices ///  /// Interface used by Media Player to determine WMP Remoting status. ///  [ComImport, ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CBB92747-741F-44fe-AB5B-F1A48F3B2A59")] public interface IWMPRemoteMediaServices { ///  /// Service type. ///  /// Remote if the control is to be remoted (attached to WMP.) /// Localif this is an independent WMP instance not connected to WMP application. If you want local, you shouldn't bother /// using this control! ///  [return: MarshalAs(UnmanagedType.BStr)] string GetServiceType(); ///  /// Value to display in Windows Media Player Switch To Application menu option (under View.) ///  ///  [return: MarshalAs(UnmanagedType.BStr)] string GetApplicationName(); ///  /// Not in use, see MSDN for details. ///  ///  ///  ///  [PreserveSig] [return: MarshalAs(UnmanagedType.U4)] HResults GetScriptableObject([MarshalAs(UnmanagedType.BStr)] out string name, [MarshalAs(UnmanagedType.IDispatch)] out object dispatch); ///  /// Not in use, see MSDN for details. ///  ///  ///  [PreserveSig] [return: MarshalAs(UnmanagedType.U4)] HResults GetCustomUIMode([MarshalAs(UnmanagedType.BStr)] out string file); } #endregion #region IOleServiceProvider ///  /// Interface used by Windows Media Player to return an instance of IWMPRemoteMediaServices. ///  [ComImport, GuidAttribute("6d5140c1-7436-11ce-8034-00aa006009fa"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown), ComVisible(true)] public interface IOleServiceProvider { ///  /// Similar to QueryInterface, riid will contain the Guid of an object to return. /// In our project we will look for  Guid and return the object /// that implements that interface. ///  ///  /// The Guid of the desired Service to provide. /// A pointer to the interface requested by the Guid. IntPtr QueryService(ref Guid guidService, ref Guid riid); } ///  /// This is an example of an INCORRECT entry - do not use, unless you want your app to break. ///  [ComImport, GuidAttribute("6d5140c1-7436-11ce-8034-00aa006009fa"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown), ComVisible(true)] public interface BadIOleServiceProvider { ///  /// This is incorrect because it causes our return interface to be boxed /// as an object and a COM callee may not get the correct pointer. ///  ///  ///  ///  ///  /// For an example of a correct definition, look at . ///  [return: MarshalAs(UnmanagedType.Interface)] object QueryService(ref Guid guidService, ref Guid riid); } #endregion #region IOleClientSite ///  /// Need to implement this interface so we can pass it to . /// All functions return E_NOTIMPL. We don't need to actually implement anything to get /// the remoting to work. ///  [ComImport, ComVisible(true), Guid("00000118-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown) ] public interface IOleClientSite { ///  /// See MSDN for more information. Throws  with id of E_NOTIMPL. ///  /// E_NOTIMPL void SaveObject(); ///  /// See MSDN for more information. Throws  with id of E_NOTIMPL. ///  /// E_NOTIMPL [return: MarshalAs(UnmanagedType.Interface)] object GetMoniker(uint dwAssign, uint dwWhichMoniker); ///  /// See MSDN for more information. Throws  with id of E_NOTIMPL. ///  /// E_NOTIMPL [return: MarshalAs(UnmanagedType.Interface)] object GetContainer(); ///  /// See MSDN for more information. Throws  with id of E_NOTIMPL. ///  /// E_NOTIMPL void ShowObject(); ///  /// See MSDN for more information. Throws  with id of E_NOTIMPL. ///  /// E_NOTIMPL void OnShowWindow(bool fShow); ///  /// See MSDN for more information. Throws  with id of E_NOTIMPL. ///  /// E_NOTIMPL void RequestNewObjectLayout(); } #endregion #region IOleObject ///  /// This interface is implemented by WMP ActiveX/COM control. /// The only function we need is . ///  [ComImport, ComVisible(true), Guid("00000112-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IOleObject { ///  /// Used to pass our custom  object to WMP. The object we pass must also /// implement  to work right. ///  /// The  to pass. void SetClientSite(IOleClientSite pClientSite); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  [return: MarshalAs(UnmanagedType.Interface)] IOleClientSite GetClientSite(); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  void SetHostNames( [MarshalAs(UnmanagedType.LPWStr)]string szContainerApp, [MarshalAs(UnmanagedType.LPWStr)]string szContainerObj); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  void Close(uint dwSaveOption); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  void SetMoniker(uint dwWhichMoniker, object pmk); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  [return: MarshalAs(UnmanagedType.Interface)] object GetMoniker(uint dwAssign, uint dwWhichMoniker); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  void InitFromData(object pDataObject, bool fCreation, uint dwReserved); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  object GetClipboardData(uint dwReserved); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  void DoVerb(uint iVerb, uint lpmsg, [MarshalAs(UnmanagedType.Interface)]object pActiveSite, uint lindex, uint hwndParent, uint lprcPosRect); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  [return: MarshalAs(UnmanagedType.Interface)] object EnumVerbs(); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  void Update(); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  [PreserveSig] [return: MarshalAs(UnmanagedType.U4)] HResults IsUpToDate(); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  Guid GetUserClassID(); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  [return: MarshalAs(UnmanagedType.LPWStr)] string GetUserType(uint dwFormOfType); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  void SetExtent(uint dwDrawAspect, [MarshalAs(UnmanagedType.Interface)] object psizel); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  [return: MarshalAs(UnmanagedType.Interface)] object GetExtent(uint dwDrawAspect); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  uint Advise([MarshalAs(UnmanagedType.Interface)]object pAdvSink); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  void Unadvise(uint dwConnection); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  [return: MarshalAs(UnmanagedType.Interface)] object EnumAdvise(); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  uint GetMiscStatus([MarshalAs(UnmanagedType.U4)] DVASPECT dwAspect); ///  /// Implemented by Windows Media Player ActiveX control. /// See MSDN for more information. ///  void SetColorScheme([MarshalAs(UnmanagedType.Interface)] object pLogpal); } #endregion }