示例#1
0
        /// <summary>
        /// Get a snapshot of the running object table (ROT).
        /// </summary>
        /// <returns>A hashtable mapping the name of the object
        //     in the ROT to the corresponding object</returns>
        private static Hashtable GetRunningObjectTable()
        {
            Hashtable result = new Hashtable();

            IntPtr numFetched = Marshal.AllocHGlobal(sizeof(int));

            IRunningObjectTable runningObjectTable;
            IEnumMoniker monikerEnumerator;
            IMoniker[] monikers = new IMoniker[1];

            GetRunningObjectTable(0, out runningObjectTable);
            runningObjectTable.EnumRunning(out monikerEnumerator);
            monikerEnumerator.Reset();

            while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
            {
                IBindCtx ctx;
                CreateBindCtx(0, out ctx);

                string runningObjectName;
                monikers[0].GetDisplayName(ctx, null, out runningObjectName);

                object runningObjectVal;
                runningObjectTable.GetObject(monikers[0], out runningObjectVal);

                result[runningObjectName] = runningObjectVal;
            }

            return result;
        }
示例#2
0
 internal static DTE2 GetCurrent()
 {
     //rot entry for visual studio running under current process.
     string rotEntry = String.Format("!VisualStudio.DTE.10.0:{0}", Process.GetCurrentProcess().Id);
     IRunningObjectTable rot;
     GetRunningObjectTable(0, out rot);
     IEnumMoniker enumMoniker;
     rot.EnumRunning(out enumMoniker);
     enumMoniker.Reset();
     IntPtr fetched = IntPtr.Zero;
     IMoniker[] moniker = new IMoniker[1];
     while (enumMoniker.Next(1, moniker, fetched) == 0)
     {
         IBindCtx bindCtx;
         CreateBindCtx(0, out bindCtx);
         string displayName;
         moniker[0].GetDisplayName(bindCtx, null, out displayName);
         if (displayName == rotEntry)
         {
             object comObject;
             rot.GetObject(moniker[0], out comObject);
             return (EnvDTE80.DTE2)comObject;
         }
     }
     return null;
 }
示例#3
0
        /// <summary>
        /// Search Running Object Table for a running VisualStudio instance which has open a particular solution.
        /// Typical usage might be EnvDTE.Solution sln = DesignTime.GetVisualStudioInstanceBySolution(@"\\My Solution\.sln$")
        /// </summary>
        /// <param name="solution_file_regex">Regular expression matching the solution fullname</param>
        /// <returns>The Solution object if a match was found, null otherwise</returns>
        public static EnvDTE.Solution GetVisualStudioInstanceBySolution(string solution_file_regex)
        {
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(solution_file_regex);

            IRunningObjectTable runningObjectTable;
            GetRunningObjectTable(0, out runningObjectTable);

            IEnumMoniker monikerEnumerator;
            runningObjectTable.EnumRunning(out monikerEnumerator);
            monikerEnumerator.Reset();

            IMoniker[] monikers = new IMoniker[1];
            IntPtr numFetched = IntPtr.Zero;
            while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
            {
                IBindCtx ctx;
                CreateBindCtx(0, out ctx);

                string runningObjectName;
                monikers[0].GetDisplayName(ctx, null, out runningObjectName);
                if (re.IsMatch(runningObjectName))
                {
                    object runningObjectVal;
                    runningObjectTable.GetObject(monikers[0], out runningObjectVal);
                    EnvDTE.Solution sln = runningObjectVal as EnvDTE.Solution;
                    if (sln != null)
                        return sln;
                }
            }

            return null;
        }
示例#4
0
文件: Ide.cs 项目: matt40k/VSAutomate
 public static DTE2 GetCurrent()
 {
     // root entry for visual studio running under current process.
     var rootEntry = $"!VisualStudio.DTE.12.0:{Process.GetCurrentProcess().Id}";
     IRunningObjectTable rot;
     NativeMethods.GetRunningObjectTable(0, out rot);
     IEnumMoniker enumMoniker;
     rot.EnumRunning(out enumMoniker);
     enumMoniker.Reset();
     var fetched = IntPtr.Zero;
     var moniker = new IMoniker[1];
     while (enumMoniker.Next(1, moniker, fetched) == 0)
     {
         IBindCtx bindCtx;
         NativeMethods.CreateBindCtx(0, out bindCtx);
         string displayName;
         moniker[0].GetDisplayName(bindCtx, null, out displayName);
         if (displayName == rootEntry)
         {
             object comObject;
             rot.GetObject(moniker[0], out comObject);
             return (DTE2)comObject;
         }
     }
     return null;
 }
示例#5
0
 public static IEnumerable<KeyValuePair<Process, EnvDTE._DTE>> GetVSInstances()
 {
     IRunningObjectTable runningObjectTable = WinApiHelper.GetRunningObjectTable();
     IEnumMoniker enumMoniker;
     runningObjectTable.EnumRunning(out enumMoniker);
     IMoniker[] monikers = new IMoniker[1];
     for(enumMoniker.Reset(); enumMoniker.Next(1, monikers, IntPtr.Zero) == 0; ) {
         EnvDTE._DTE dte;
         Process dteProcess;
         try {
             IBindCtx ctx = WinApiHelper.NewBindCtx();
             string runningObjectName;
             monikers[0].GetDisplayName(ctx, null, out runningObjectName);
             if(!runningObjectName.StartsWith("!VisualStudio") && !runningObjectName.StartsWith("!WDExpress.DTE")) continue;
             object runningObjectVal;
             runningObjectTable.GetObject(monikers[0], out runningObjectVal);
             dte = runningObjectVal as EnvDTE._DTE;
             if(dte == null) continue;
             int dteProcessId = int.Parse(runningObjectName.Split(':')[1]);
             dteProcess = Process.GetProcessById(dteProcessId);
         } catch {
             continue;
         }
         yield return new KeyValuePair<Process, EnvDTE._DTE>(dteProcess, dte);
     }
 }
示例#6
0
        public static DTE GetDTE(string processID)
        {
            IRunningObjectTable prot;
            IEnumMoniker pMonkEnum;

            string progID = "!VisualStudio.DTE.8.0:" + processID;

            GetRunningObjectTable(0, out prot);
            prot.EnumRunning(out pMonkEnum);
            pMonkEnum.Reset();

            IntPtr fetched = IntPtr.Zero;
            IMoniker[] pmon = new IMoniker[1];
            while (pMonkEnum.Next(1, pmon, fetched) == 0)
            {
                IBindCtx pCtx;
                CreateBindCtx(0, out pCtx);
                string str;
                pmon[0].GetDisplayName(pCtx, null, out str);
                if (str == progID)
                {
                    object objReturnObject;
                    prot.GetObject(pmon[0], out objReturnObject);
                    DTE ide = (DTE)objReturnObject;
                    return ide;
                }
            }

            return null;
        }
示例#7
0
        /// <summary>
        /// Retrieve the running object table
        /// </summary>
        /// <returns>A hashtable containing the running objects</returns>
        private static Hashtable GetRunningObjectTable()
        {
            Hashtable result;
            IntPtr numFetched;
            IRunningObjectTable runningObjectTable;
            IEnumMoniker monikerEnumerator;
            IMoniker[] monikers;
            IBindCtx ctx;

            result = new Hashtable();
            numFetched = new IntPtr();
            monikers = new IMoniker[1];

            GetRunningObjectTable(0, out runningObjectTable);
            runningObjectTable.EnumRunning(out monikerEnumerator);
            monikerEnumerator.Reset();
            CreateBindCtx(0, out ctx);

            while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
            {
                string displayName;
                object comObject;
                monikers[0].GetDisplayName(ctx, null, out displayName);

                runningObjectTable.GetObject(monikers[0], out comObject);
                result[displayName] = comObject;
            }

            return result;
        }
示例#8
0
        /// <summary>
        /// Gets the available Visual Studio DTE2
        /// </summary>
        public static List<DTE2> GetDTEs()
        {
            List<DTE2> dte2s = new List<DTE2>();

            IRunningObjectTable rot;
            GetRunningObjectTable(0, out rot);
            IEnumMoniker enumMoniker;
            rot.EnumRunning(out enumMoniker);
            enumMoniker.Reset();
            IntPtr fetched = IntPtr.Zero;
            IMoniker[] moniker = new IMoniker[1];
            while (enumMoniker.Next(1, moniker, fetched) == 0)
            {
                IBindCtx bindCtx;
                CreateBindCtx(0, out bindCtx);
                string displayName;
                moniker[0].GetDisplayName(bindCtx, null, out displayName);
                // add all VisualStudio ROT entries to list
                if (displayName.StartsWith("!VisualStudio"))
                {
                    object comObject;
                    rot.GetObject(moniker[0], out comObject);
                    dte2s.Add((DTE2)comObject);
                }
            }
            return dte2s;
        }
 public static DTE2 GetByID(int ID)
 {
     //rot entry for visual studio running under current process.
     string rotEntry = String.Format("!VisualStudio.DTE.10.0:{0}", ID);
     IRunningObjectTable rot;
     GetRunningObjectTable(0, out rot);
     IEnumMoniker enumMoniker;
     rot.EnumRunning(out enumMoniker);
     enumMoniker.Reset();
     IntPtr fetched = IntPtr.Zero;
     IMoniker[] moniker = new IMoniker[1];
     while (enumMoniker.Next(1, moniker, fetched) == 0)
     {
         IBindCtx bindCtx;
         CreateBindCtx(0, out bindCtx);
         string displayName;
         moniker[0].GetDisplayName(bindCtx, null, out displayName);
         if (displayName.StartsWith("!VisualStudio.DTE.", StringComparison.OrdinalIgnoreCase) &&
                 displayName.EndsWith(ID.ToString()))
         {
             object comObject;
             rot.GetObject(moniker[0], out comObject);
             return (EnvDTE80.DTE2)comObject;
         }
     }
     return null;
 }
示例#10
0
        public static IEnumerable<KeyValuePair<int, object>> GetE3Applications()
        {
            IRunningObjectTable runningObjectTable;
            IEnumMoniker monikerEnumerator;
            var monikers = new IMoniker[1];

            IBindCtx ctx;
            WinApi.CreateBindCtx(0, out ctx);

            ctx.GetRunningObjectTable(out runningObjectTable);
            runningObjectTable.EnumRunning(out monikerEnumerator);
            monikerEnumerator.Reset();

            while (monikerEnumerator.Next(1, monikers, IntPtr.Zero) == 0)
            {
                string runningObjectName;
                monikers[0].GetDisplayName(ctx, null, out runningObjectName);

                if (!runningObjectName.StartsWith("!E3Application", StringComparison.InvariantCultureIgnoreCase))
                    continue;

                int index = runningObjectName.IndexOf(':');
                if (index == -1) continue;

                object runningObjectVal;
                runningObjectTable.GetObject(monikers[0], out runningObjectVal);

                yield return
                    new KeyValuePair<int, object>(int.Parse(runningObjectName.Substring(index + 1)),
                        runningObjectVal);
            }
        }
示例#11
0
        public static bool GetDevicesOfCat(Guid cat, out ArrayList devs)
        {
            devs = null;
            int hr;
            object comObj = null;
            ICreateDevEnum enumDev = null;
            IEnumMoniker enumMon = null;
            IMoniker[] mon = new IMoniker[1];
            try
            {
                Type srvType = Type.GetTypeFromCLSID(Clsid.SystemDeviceEnum);
                if (srvType == null)
                    throw new NotImplementedException("System Device Enumerator");

                comObj = Activator.CreateInstance(srvType);
                enumDev = (ICreateDevEnum)comObj;
                hr = enumDev.CreateClassEnumerator(ref cat, out enumMon, 0);
                if (hr != 0)
                    throw new NotSupportedException("No devices of the category");

                int count = 0;
                IntPtr f = IntPtr.Zero;
                do
                {
                    hr = enumMon.Next(1, mon, f);
                    if ((hr != 0) || (mon[0] == null))
                        break;
                    DsDevice dev = new DsDevice();
                    dev.Name = GetFriendlyName(mon[0]);
                    if (devs == null)
                        devs = new ArrayList();
                    dev.Mon = mon[0]; mon[0] = null;
                    devs.Add(dev); dev = null;
                    count++;
                }
                while (true);

                return count > 0;
            }
            catch (Exception)
            {
                if (devs != null)
                {
                    foreach (DsDevice d in devs)
                        d.Dispose();
                    devs = null;
                }
                return false;
            }
            finally
            {
                enumDev = null;
                if (mon[0] != null)
                    Marshal.ReleaseComObject(mon[0]); mon[0] = null;
                if (enumMon != null)
                    Marshal.ReleaseComObject(enumMon); enumMon = null;
                if (comObj != null)
                    Marshal.ReleaseComObject(comObj); comObj = null;
            }
        }
示例#12
0
        public static IEnumerable<DTE> GetInstances()
        {
            IRunningObjectTable rot;
            IEnumMoniker enumMoniker;
            int retVal = GetRunningObjectTable(0, out rot);

            if (retVal == 0)
            {
                rot.EnumRunning(out enumMoniker);

                IntPtr fetched = IntPtr.Zero;
                IMoniker[] moniker = new IMoniker[1];
                while (enumMoniker.Next(1, moniker, fetched) == 0)
                {
                    IBindCtx bindCtx;
                    CreateBindCtx(0, out bindCtx);
                    string displayName;
                    moniker[0].GetDisplayName(bindCtx, null, out displayName);
                    Console.WriteLine("Display Name: {0}", displayName);
                    bool isVisualStudio = displayName.StartsWith("!VisualStudio");
                    if (isVisualStudio)
                    {
                        object dte = null;
                        //var dte = rot.GetObject(moniker) as DTE;
                        var x = rot.GetObject(moniker[0], out dte);
                        yield return dte as DTE;
                    }
                }
            }
        }
示例#13
0
        /// <summary>
        /// Return S_OK (0) so that IE will stop to download the file itself. 
        /// Else the default download user interface is used.
        /// </summary>
        public int Download(IMoniker pmk, IBindCtx pbc, uint dwBindVerb, int grfBINDF, 
            IntPtr pBindInfo, string pszHeaders, string pszRedir, uint uiCP)
        {
            // Get the display name of the pointer to an IMoniker interface that specifies
            // the object to be downloaded.
            string name = string.Empty;
            pmk.GetDisplayName(pbc, null, out name);

            if (!string.IsNullOrEmpty(name))
            {
                Uri url = null;
                bool result = Uri.TryCreate(name, UriKind.Absolute, out url);

                if (result)
                {
                    MessageBox.Show(url.ToString());
                    //pmk.BindToStorage(pbc,null,);

                    //// Launch CSWebDownloader.exe to download the file.
                    //FileInfo assemblyFile =
                    //    new FileInfo(Assembly.GetExecutingAssembly().Location);
                    //ProcessStartInfo start = new ProcessStartInfo
                    //{
                    //    Arguments = name,
                    //    FileName =
                    //    string.Format("{0}\\CSWebDownloader.exe", assemblyFile.DirectoryName)
                    //};
                    //Process.Start(start);
                    return 0;
                }
            }
            return 1;
        }
示例#14
0
		/// <summary> Retrieve the human-readable name of the filter </summary>
		protected string getName(IMoniker moniker)
		{
			object bagObj = null;
			IPropertyBag bag = null;
			try 
			{
				Guid bagId = typeof( IPropertyBag ).GUID;
				moniker.BindToStorage( null, null, ref bagId, out bagObj );
				bag = (IPropertyBag) bagObj;
				object val = "";
				int hr = bag.Read( "FriendlyName", ref val, IntPtr.Zero );
				//if( hr != 0 )
				//	Marshal.ThrowExceptionForHR( hr );
				string ret = val as string;
				if( (ret == null) || (ret.Length < 1) )
					throw new NotImplementedException( "Device FriendlyName" );
				return( ret );
			}
			catch( Exception )
			{
				return( "" );
			}
			finally
			{
				bag = null;
				if( bagObj != null )
					Marshal.ReleaseComObject( bagObj ); bagObj = null;
			}
		}
示例#15
0
        public static List<string> GetRunningObjectTableNames()
        {
            IRunningObjectTable runningObjectTable;
            GetRunningObjectTable(0, out runningObjectTable);

            IEnumMoniker monikers;
            runningObjectTable.EnumRunning(out monikers);

            IMoniker[] moniker = new IMoniker[1];
            List<string> names = new List<string>();

            monikers.Reset();

            int result = 0;
            while (result == 0)
            {
            unsafe
            {
            int count;
            System.IntPtr pCount = (System.IntPtr)(&count);
            result = monikers.Next(1, moniker, pCount);
            }
            if (result != 0)
            break;

            IBindCtx context;
            CreateBindCtx(0, out context);

            string name;
            moniker[0].GetDisplayName(context, null, out name);

            names.Add(name);
            }
            return names;
        }
示例#16
0
        /// <summary>
        /// Get a snapshot of the running object table (ROT).
        /// </summary>
        /// <param name="filter">The filter to apply to the list (nullable).</param>
        /// <returns>A hashtable of the matching entries in the ROT</returns>
        public static Hashtable GetActiveObjectList(string filter)
        {
            var result = new Hashtable();

            IntPtr numFetched = IntPtr.Zero;
            IRunningObjectTable runningObjectTable;
            IEnumMoniker monikerEnumerator;
            var monikers = new IMoniker[1];

            NativeMethods.GetRunningObjectTable(0, out runningObjectTable);
            runningObjectTable.EnumRunning(out monikerEnumerator);
            monikerEnumerator.Reset();

            while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
            {
                IBindCtx ctx;
                NativeMethods.CreateBindCtx(0, out ctx);

                string runningObjectName;
                monikers[0].GetDisplayName(ctx, null, out runningObjectName);

                object runningObjectVal;
                runningObjectTable.GetObject(monikers[0], out runningObjectVal);
                if (string.IsNullOrEmpty(filter) || runningObjectName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    result[runningObjectName] = runningObjectVal;
                }
            }

            return result;
        }
示例#17
0
        // Get moniker string of the moniker
		private string GetMonikerString(IMoniker moniker)
		{
			string str;
			moniker.GetDisplayName(null, null, out str);

			return str;
		}
示例#18
0
        internal Filter(IMoniker moniker)
#endif
#endif
		{
			Name = getName( moniker );
			MonikerString = getMonikerString( moniker );
		}
示例#19
0
        /// <summary>
        /// Initializes camera, builds and runs graph for control.
        /// </summary>
        /// <param name="moniker">Moniker (device identification) of camera.</param>
        /// <param name="resolution">Resolution of camera's output.</param>
        public void SetCamera(IMoniker moniker, Resolution resolution)
        {
            // Close current if it was opened
            CloseCamera();

            if (moniker == null)
                return;

            // Create camera object
            _Camera = new Camera();

            if (!string.IsNullOrEmpty(_DirectShowLogFilepath))
                _Camera.DirectShowLogFilepath = _DirectShowLogFilepath;

            // select resolution
            //ResolutionList resolutions = Camera.GetResolutionList(moniker);

            if (resolution != null)
            {
                _Camera.Resolution = resolution;
            }

            // Initialize
            _Camera.Initialize(this, moniker);

            // Build and Run graph
            _Camera.BuildGraph();
            _Camera.RunGraph();


            _Camera.OutputVideoSizeChanged += Camera_OutputVideoSizeChanged;
        }
示例#20
0
 void IMoniker.BindToStorage(IBindCtx pbc, IMoniker pmkToLeft, ref Guid riid, out object ppvObj)
 {
     ppvObj = null;
     if (riid.Equals(Iid_Clsids.IID_IStream))
     {
         ppvObj = this.m_stream;
     }
 }
示例#21
0
		protected string getMonikerString(IMoniker moniker)
#endif
#endif
		{
			string s;
			moniker.GetDisplayName( null, null, out s );
			return( s );
		}
示例#22
0
        internal static DTE GetInstance(string solution)
        {
            const string visualStudioProgId = "!VisualStudio.DTE.";

            IRunningObjectTable runningObjectTable = null;
            IEnumMoniker enumMoniker = null;
            IBindCtx bindCtx = null;

            try
            {
                Marshal.ThrowExceptionForHR(GetRunningObjectTable(0, out runningObjectTable));
                runningObjectTable.EnumRunning(out enumMoniker);

                IMoniker[] monikers = new IMoniker[1];
                enumMoniker.Reset();

                Marshal.ThrowExceptionForHR(CreateBindCtx(0, out bindCtx));

                while (enumMoniker.Next(1, monikers, IntPtr.Zero) == 0)
                {
                    string displayName;
                    monikers[0].GetDisplayName(bindCtx, null, out displayName);

                    if (displayName.StartsWith(visualStudioProgId))
                    {
                        object o;
                        Marshal.ThrowExceptionForHR(runningObjectTable.GetObject(monikers[0], out o));

                        var d = (DTE)o;

                        if (d.Solution.FullName.EndsWith(solution, StringComparison.InvariantCultureIgnoreCase)) return d;
                    }
                }
            }
            finally
            {
                if (runningObjectTable != null)
                {
                    Marshal.ReleaseComObject(runningObjectTable);
                }

                if (enumMoniker != null)
                {
                    Marshal.ReleaseComObject(enumMoniker);
                }

                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }

            return null;
        }
示例#23
0
        static ExcelInstance()
        {
            Hashtable result = new Hashtable();

            IntPtr numFetched = IntPtr.Zero;
            IRunningObjectTable runningObjectTable;
            IEnumMoniker monikerEnumerator;
            IMoniker[] monikers = new IMoniker[1];

            GetRunningObjectTable(0, out runningObjectTable);
            runningObjectTable.EnumRunning(out monikerEnumerator);
            monikerEnumerator.Reset();

            while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
            {
                System.Runtime.InteropServices.ComTypes.IBindCtx ctx;
                CreateBindCtx(0, out ctx);

                string runningObjectName;
                monikers[0].GetDisplayName(ctx, null, out runningObjectName);

                object runningObjectVal;
                runningObjectTable.GetObject(monikers[0], out runningObjectVal);

                if (runningObjectVal is XL._Workbook)
                {
                    XL._Workbook theExcel = (XL._Workbook)runningObjectVal;
                    int theHandle = theExcel.Application.Hwnd;
                    int ProcessId;
                    GetWindowThreadProcessId(theHandle, out ProcessId);
                    if (ProcessId == Process.GetCurrentProcess().Id)
                    {
                        theInstance=theExcel.Application;
                        return;
                    }

                }
                if (runningObjectVal is XL._Application)
                {
                    XL._Application theExcel = (XL._Application)runningObjectVal;
                    int theHandle = theExcel.Hwnd;
                    int ProcessId;
                    GetWindowThreadProcessId(theHandle, out ProcessId);
                    if (ProcessId == Process.GetCurrentProcess().Id)
                    {
                        theInstance = (XL._Application)runningObjectVal;
                        return;
                    }

                }
            }
            throw new Exception("Didn't get a Handle");
        }
示例#24
0
        public static DsDevice[] GetDevicesOfCat(Guid FilterCategory)
        {
            DsDevice[] devret;
            var devs = new ArrayList();
            IEnumMoniker enumMon;
            var enumDev = (ICreateDevEnum)new CreateDevEnum();
            var hr = enumDev.CreateClassEnumerator(FilterCategory, out enumMon, 0);
            DsError.ThrowExceptionForHR(hr);

            if (hr != 1)
            {
                try
                {
                    try
                    {
                        var mon = new IMoniker[1];
                        while ((enumMon.Next(1, mon, IntPtr.Zero) == 0))
                        {
                            try
                            {
                                devs.Add(new DsDevice(mon[0]));
                            }
                            catch
                            {
                                Marshal.ReleaseComObject(mon[0]);
                                throw;
                            }
                        }
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(enumMon);
                    }

                    devret = new DsDevice[devs.Count];
                    devs.CopyTo(devret);
                }
                catch
                {
                    foreach (DsDevice d in devs)
                    {
                        d.Dispose();
                    }
                    throw;
                }
            }
            else
            {
                devret = new DsDevice[0];
            }

            return devret;
        }
示例#25
0
		public static void ROTRegisterAsRunning(IMoniker new_moniker, object o, ref int rot_cookie, Type intf)
		{
			// Revoke any existing file moniker. See Brockschmidt, Inside Ole 2nd ed. p988
			ROTUnregister(ref rot_cookie);

			// Register the moniker in the running object table (ROT).
			ComDebug.ReportInfo("Registering {0} in ROT", DataObjectHelper.GetDisplayName(new_moniker));
			IRunningObjectTable rot = GetROT();

			// This flag solved a terrible problem where Word would stop
			// communicating after its first call to GetObject().
			rot_cookie = rot.Register(1 /*ROTFLAGS_REGISTRATIONKEEPSALIVE*/, o, new_moniker);
		}
示例#26
0
        private static object GetDteFromRot(int processId)
        {
            IRunningObjectTable runningObjectTable;
            IEnumMoniker monikerEnumerator;

            string expectedMonikerEnd = String.Format(CultureInfo.InvariantCulture, "DTE.11.0:{0}", processId);

            try
            {
                uint hResult = GetRunningObjectTable(0, out runningObjectTable);
                if (hResult != 0)
                {
                    return null;
                }

                runningObjectTable.EnumRunning(out monikerEnumerator);
                monikerEnumerator.Reset();

                IntPtr numberFetched = IntPtr.Zero;
                IMoniker[] monikers = new IMoniker[1];
                while (monikerEnumerator.Next(1, monikers, numberFetched) == 0)
                {
                    IBindCtx ctx;
                    hResult = CreateBindCtx(0, out ctx);
                    if (hResult != 0)
                    {
                        // release the bind ctx obj
                        Marshal.ReleaseComObject(ctx);
                        continue;
                    }

                    string runningObjectName;
                    monikers[0].GetDisplayName(ctx, null, out runningObjectName);
                    // release the bind ctx obj
                    Marshal.ReleaseComObject(ctx);

                    if (runningObjectName.EndsWith(expectedMonikerEnd))
                    {
                        object runningObjectValue;
                        int hRes = runningObjectTable.GetObject(monikers[0], out runningObjectValue);
                        return hRes != 0 ? null : runningObjectValue as EnvDTE._DTE; 
                    }
                }
            }
            catch(Exception e)
            {
                Trace.TraceError(e.ToString());
            }
            return null;
        } 
示例#27
0
 public static Moniker[] EnumRunning() {
     IRunningObjectTable prot;
     GetRunningObjectTable(0, out prot);
     try {
         IEnumMoniker penumMoniker;
         prot.EnumRunning(out penumMoniker);
         try {
             ArrayList al = new ArrayList();
             IMoniker[] gelt = new IMoniker[] { null };
             while (penumMoniker.Next(1, gelt, IntPtr.Zero) == 0) {
                 al.Add(new Moniker(gelt[0]));
             }
             return (Moniker[])al.ToArray(typeof(Moniker));
         }
         finally { Marshal.ReleaseComObject(penumMoniker); }
     }
     finally { Marshal.ReleaseComObject(prot); }
 }
示例#28
0
        public DSGrapheditROTEntry(string displayName, IMoniker mon)
        {
            _rotDisplayName = displayName;
            _mon = mon;

            // parse the pointers
            string[] tokens = displayName.Split(' ');
            if (tokens.Length == 4)
            {
                _filterPtr = new IntPtr(Convert.ToInt64(tokens[1], 16));
                _pid = Convert.ToInt32(tokens[3], 16);
            }

            Process proc = Process.GetProcessById(_pid);
            if (proc != null)
            {
                _processName = proc.ProcessName;
            }
        }
        /// <summary>
        /// Enumerates the list of monikers of all the objects currently
        /// registered in the running object table (ROT).
        /// </summary>
        /// <param name="rot">The running object table (ROT).</param>
        /// <returns>An enumeration of the monikers of the objects in the ROT.</returns>
        public static IEnumerable<IMoniker> EnumRunningObjects(this IRunningObjectTable rot)
        {
            var monikers = new IMoniker[1];

            // Creates and returns a pointer to an enumerator that can list the monikers
            // of all the objects currently registered in the running object table (ROT).
            IEnumMoniker enumMoniker;
            rot.EnumRunning(out enumMoniker);

            // Resets the enumeration sequence to the beginning.
            enumMoniker.Reset();

            // TODO: Create safe wrapper for each IMoniker to call Release?
            // Retrieves one item at a time in the enumeration sequence.
            while (enumMoniker.Next(1, monikers, IntPtr.Zero) == Win32Error.ERROR_SUCCESS)
            {
                yield return monikers[0];
            }
        }
示例#30
0
        void LoadROT()
        {
            IBindCtx bindCtx;

            listViewROT.Items.Clear();
            try
            {
                bindCtx = COMUtilities.CreateBindCtx(0);
                IRunningObjectTable rot;
                IEnumMoniker enumMoniker;
                IMoniker[] moniker = new IMoniker[1];

                bindCtx.GetRunningObjectTable(out rot);
                rot.EnumRunning(out enumMoniker);
                while (enumMoniker.Next(1, moniker, IntPtr.Zero) == 0)
                {
                    string strDisplayName;
                    Guid clsid;

                    moniker[0].GetDisplayName(bindCtx, null, out strDisplayName);
                    moniker[0].GetClassID(out clsid);
                    ListViewItem item = listViewROT.Items.Add(strDisplayName);
                    item.Tag = new MonikerInfo(strDisplayName, clsid, moniker[0]);

                    if (m_reg.Clsids.ContainsKey(clsid))
                    {
                        item.SubItems.Add(m_reg.Clsids[clsid].Name);
                    }
                    else
                    {
                        item.SubItems.Add(clsid.ToString("B"));
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }

            listViewROT.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        }
示例#31
0
 void IOleObject.SetMoniker(uint dwWhichMoniker, IMoniker pmk)
 {
     throw new NotImplementedException();
 }
示例#32
0
 public DsDevice(IMoniker mon)
 {
     Moniker = mon;
     _name   = null;
 }
示例#33
0
        public static bool GetDevicesOfCat(Guid cat, out ArrayList devs)
        {
            devs = null;
            int            hr;
            object         comObj  = null;
            ICreateDevEnum enumDev = null;
            IEnumMoniker   enumMon = null;

            IMoniker[] mon = new IMoniker[1];
            try {
                Type srvType = Type.GetTypeFromCLSID(Clsid.SystemDeviceEnum);
                if (srvType == null)
                {
                    throw new NotImplementedException("System Device Enumerator");
                }

                comObj  = Activator.CreateInstance(srvType);
                enumDev = (ICreateDevEnum)comObj;
                hr      = enumDev.CreateClassEnumerator(ref cat, out enumMon, 0);
                if (hr != 0)
                {
                    throw new NotSupportedException("No devices of the category");
                }

                IntPtr f     = IntPtr.Zero;
                int    count = 0;
                do
                {
                    hr = enumMon.Next(1, mon, f);
                    if ((hr != 0) || (mon[0] == null))
                    {
                        break;
                    }
                    DsDevice dev = new DsDevice();
                    dev.Name = GetFriendlyName(mon[0]);
                    if (devs == null)
                    {
                        devs = new ArrayList();
                    }
                    dev.Mon            = mon[0]; mon[0] = null;
                    devs.Add(dev); dev = null;
                    count++;
                }while(true);

                return(count > 0);
            }
            catch (Exception)
            {
                if (devs != null)
                {
                    foreach (DsDevice d in devs)
                    {
                        d.Dispose();
                    }
                    devs = null;
                }
                return(false);
            }
            finally
            {
                enumDev = null;
                if (mon[0] != null)
                {
                    Marshal.ReleaseComObject(mon[0]);
                }
                mon[0] = null;
                if (enumMon != null)
                {
                    Marshal.ReleaseComObject(enumMon);
                }
                enumMon = null;
                if (comObj != null)
                {
                    Marshal.ReleaseComObject(comObj);
                }
                comObj = null;
            }
        }
示例#34
0
 //
 // Get moniker string of the moniker
 //
 private string GetMonikerString(IMoniker moniker)
 {
     moniker.GetDisplayName(null, null, out string str);
     return(str);
 }
示例#35
0
    public static DTE GetDTE(int processId)
    {
        string progId        = "!VisualStudio.DTE.16.0:" + processId.ToString();
        object runningObject = null;

        IBindCtx            bindCtx      = null;
        IRunningObjectTable rot          = null;
        IEnumMoniker        enumMonikers = null;

        try
        {
            Marshal.ThrowExceptionForHR(CreateBindCtx(reserved: 0, ppbc: out bindCtx));
            bindCtx.GetRunningObjectTable(out rot);
            rot.EnumRunning(out enumMonikers);

            IMoniker[] moniker       = new IMoniker[1];
            IntPtr     numberFetched = IntPtr.Zero;
            while (enumMonikers.Next(1, moniker, numberFetched) == 0)
            {
                IMoniker runningObjectMoniker = moniker[0];

                string name = null;

                try
                {
                    if (runningObjectMoniker != null)
                    {
                        runningObjectMoniker.GetDisplayName(bindCtx, null, out name);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    // Do nothing, there is something in the ROT that we do not have access to.
                }

                if (!string.IsNullOrEmpty(name) &&
                    name.StartsWith("!VisualStudio.DTE.") &&
                    name.EndsWith(processId.ToString()))
                {
                    Marshal.ThrowExceptionForHR(rot.GetObject(runningObjectMoniker, out runningObject));
                    break;
                }
            }
        }
        finally
        {
            if (enumMonikers != null)
            {
                Marshal.ReleaseComObject(enumMonikers);
            }

            if (rot != null)
            {
                Marshal.ReleaseComObject(rot);
            }

            if (bindCtx != null)
            {
                Marshal.ReleaseComObject(bindCtx);
            }
        }

        return((DTE)runningObject);
    }
示例#36
0
        public DSFilterTreeViewNode(DsDevice device, Guid dmoCategory)
        {
            _filterName = GetFriendlyName(device.Mon);
            Text        = _filterName;
            _moniker    = device.Mon;
            _devicePath = device.DevicePath;

            // get the type of the filter from the device path
            if (_devicePath.StartsWith("@device:sw"))
            {
                _filterType = FilterType.DefaultFilter;
            }
            else if (_devicePath.StartsWith("@device:dmo"))
            {
                _filterType = FilterType.DMO;
            }
            else if (_devicePath.StartsWith("@device:cm"))
            {
                _filterType = FilterType.CompressionManager;
            }
            else if (_devicePath.StartsWith("@device:pnp"))
            {
                _filterType = FilterType.PnP;
            }
            else
            {
                _filterType = FilterType.KSProxy;
            }

            _dmoCategory = dmoCategory;
            if (DSFilterType == FilterType.DMO)
            {
                _classGuid = FindDMOGuid(_filterName, dmoCategory);
            }
            else
            {
                _classGuid = GetMonikerGuid(device.Mon);
            }

            if (_classGuid != Guid.Empty)
            {
                // try to get the path to the clsid from the registry
                RegistryKey clsidKey = Registry.ClassesRoot.OpenSubKey("CLSID\\{" + _classGuid.ToString() + "}\\InprocServer32\\");
                if (clsidKey != null)
                {
                    try
                    {
                        _filePath = (string)clsidKey.GetValue("");

                        if (_filePath.ToLower().EndsWith("mscoree.dll"))
                        {
                            // YOU LIE!!! it's actually a .Net assembly masquerading as a COM clsid
                            _filePath = (string)clsidKey.GetValue("Assembly");
                        }
                    }
                    catch { }
                    finally
                    {
                        clsidKey.Close();
                    }
                }

                // color code according to the Filter Type
                switch (_filterType)
                {
                case FilterType.DefaultFilter:
                    ForeColor = Color.Black;
                    break;

                case FilterType.DMO:
                    ForeColor = Color.Green;
                    break;

                case FilterType.KSProxy:
                    ForeColor = Color.Red;
                    break;

                case FilterType.CompressionManager:
                    ForeColor = Color.Blue;
                    break;

                case FilterType.PnP:
                    ForeColor = Color.Purple;
                    break;

                default:
                    break;
                }

                // parse the filter data from the moniker
                _filterData = new FilterData(device.Mon);
            }
        }
示例#37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FilterInfo"/> class.
 /// </summary>
 ///
 /// <param name="moniker">Filter's moniker object.</param>
 ///
 internal FilterInfo(IMoniker moniker)
 {
     MonikerString = GetMonikerString(moniker);
     Name          = GetName(moniker);
 }
示例#38
0
        public AudioEncoderCollection()
        {
            ICreateDevEnum deviceEnumerator = null;

            try
            {
                deviceEnumerator = (ICreateDevEnum) new CreateDevEnum();

                IEnumMoniker monikerEnum = null;

                try
                {
                    int hr =
                        deviceEnumerator.CreateClassEnumerator(FilterGraphTools.CLSID_AudioCompressorCategory,
                                                               out monikerEnum, CDef.None);
                    DsError.ThrowExceptionForHR(hr);

                    IMoniker[] monikers = new IMoniker[1];

                    while (true)
                    {
                        try
                        {
                            hr = monikerEnum.Next(1, monikers, IntPtr.Zero);

                            DsError.ThrowExceptionForHR(hr);

                            object bag;

                            Guid id = FilterGraphTools.IID_IPropertyBag;

                            if (monikers[0] == null)
                            {
                                break;
                            }

                            monikers[0].BindToStorage(null, null, ref id, out bag);

                            IPropertyBag propertyBag = (IPropertyBag)bag;

                            Marshal.ReleaseComObject(propertyBag);

                            object variantName;
                            hr = propertyBag.Read("FriendlyName", out variantName, null);
                            DsError.ThrowExceptionForHR(hr);

                            string friendlyName = Convert.ToString(variantName);

                            Guid id2 = FilterGraphTools.IID_IBaseFilter;

                            object filter;

                            monikers[0].BindToObject(null, null, ref id2, out filter);

                            if (filter != null)
                            {
                                _encoders.Add(new AudioEncoder(friendlyName, (IBaseFilter)filter));
                            }
                        }
                        finally
                        {
                            if (monikers[0] != null)
                            {
                                Marshal.ReleaseComObject(monikers[0]);
                            }
                        }
                    }
                }
                finally
                {
                    if (monikerEnum != null)
                    {
                        Marshal.ReleaseComObject(monikerEnum);
                    }
                }
            }
            finally
            {
                if (deviceEnumerator != null)
                {
                    Marshal.ReleaseComObject(deviceEnumerator);
                }
            }
        }
 /// <summary> Create a new filter from its moniker </summary>
 internal Filter(IMoniker moniker)
 {
     Name          = getName(moniker);
     MonikerString = getMonikerString(moniker);
 }
示例#40
0
 public static extern int CreateGenericComposite(IMoniker pmkFirst, IMoniker pmkRest, out IMoniker ppmkComposite);
示例#41
0
 void IOleObject.GetMoniker(uint dwAssign, uint dwWhichMoniker, out IMoniker ppmk)
 {
     throw new NotImplementedException();
 }
示例#42
0
 static extern int CreateClassMoniker([In] ref Guid rclsid,
                                      out IMoniker ppmk);
示例#43
0
 public static extern void CreateItemMoniker(
     [MarshalAs(UnmanagedType.LPWStr)] string lpszDelim,
     [MarshalAs(UnmanagedType.LPWStr)] string lpszItem,
     out IMoniker ppmk);
示例#44
0
        /// <summary>
        /// Only public method which starts the parsing process
        /// When parsing is done, we receive a DISPID_READYSTATE dispid
        /// in IPropertyNotifySink.OnChanged implementation
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="cookie"></param>
        public void StartParsing(string Url, string cookie)
        {
            IntPtr pUsername = IntPtr.Zero;
            IntPtr pPassword = IntPtr.Zero;

            try
            {
                if (string.IsNullOrEmpty(Url))
                {
                    throw new ApplicationException("Url must have a valid value!");
                }

                //Create a new MSHTML, throws exception if fails
                Type htmldoctype = Type.GetTypeFromCLSID(Iid_Clsids.CLSID_HTMLDocument, true);
                //Using Activator inplace of CoCreateInstance, returns IUnknown
                //which we cast to a IHtmlDocument2 interface
                m_pMSHTML = (IHTMLDocument2)System.Activator.CreateInstance(htmldoctype);

                //Get the IOleObject
                m_WBOleObject = (IOleObject)m_pMSHTML;
                //Set client site
                int iret = m_WBOleObject.SetClientSite(this);

                //Connect for IPropertyNotifySink
                m_WBOleControl = (IOleControl)m_pMSHTML;
                m_WBOleControl.OnAmbientPropertyChange(HTMLDispIDs.DISPID_AMBIENT_DLCONTROL);

                //Get connectionpointcontainer
                IConnectionPointContainer cpCont = (IConnectionPointContainer)m_pMSHTML;
                cpCont.FindConnectionPoint(ref Iid_Clsids.IID_IPropertyNotifySink, out m_WBConnectionPoint);
                //Advice
                m_WBConnectionPoint.Advise(this, out m_dwCookie);

                m_Done = false;
                m_Url  = Url;

                if (!string.IsNullOrEmpty(cookie))
                {
                    m_pMSHTML.cookie = cookie;
                }

                //Set up username and password if provided
                pUsername = Marshal.StringToCoTaskMemAnsi(m_Username);
                if (pUsername != IntPtr.Zero)
                {
                    WinApis.InternetSetOption(IntPtr.Zero,
                                              InternetSetOptionFlags.INTERNET_OPTION_USERNAME,
                                              pUsername, m_Username.Length);
                }
                pPassword = Marshal.StringToCoTaskMemAnsi(m_Password);
                if (pPassword != IntPtr.Zero)
                {
                    WinApis.InternetSetOption(IntPtr.Zero,
                                              InternetSetOptionFlags.INTERNET_OPTION_PASSWORD,
                                              pPassword, m_Password.Length);
                }

                //Load
                IPersistMoniker persistMoniker = (IPersistMoniker)m_pMSHTML;
                IMoniker        moniker        = null;
                WinApis.CreateURLMoniker(null, m_Url, out moniker);
                if (moniker == null)
                {
                    return;
                }
                IBindCtx bindContext = null;
                WinApis.CreateBindCtx((uint)0, out bindContext);
                if (bindContext == null)
                {
                    return;
                }
                persistMoniker.Load(1, moniker, bindContext, 0);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (pUsername != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pUsername);
                }
                if (pPassword != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pPassword);
                }
            }
        }
示例#45
0
 public static extern int CreateURLMoniker(
     [In] IMoniker pmkContext,
     [In, MarshalAs(UnmanagedType.LPWStr)]  string szURL,
     [Out] out IMoniker ppmk);
示例#46
0
        /// <summary>
        /// Visual Studioデバッガーにアタッチします。
        /// </summary>
        /// <param name="debuggerInfo">現在のプロセスをアタッチするデバッガー情報。</param>
        /// <returns><paramref name="debuggerInfo" />がVisual Studioのデバッガー情報で、アタッチに成功した場合は<c>True</c>。その他の場合は<c>False</c>。</returns>
        public override bool AttachToType(DebuggerInfo debuggerInfo)
        {
            if (debuggerInfo == null ||
                debuggerInfo.DebuggerType != typeof(VisualStudioDebuggerInfoProvider) ||
                !(debuggerInfo.ProcessId > 0))
            {
                return(false);
            }

            IBindCtx            bc          = null;
            IRunningObjectTable rot         = null;
            IEnumMoniker        enumMoniker = null;

            try
            {
                var r = NativeMethods.CreateBindCtx(0, out bc);
                Marshal.ThrowExceptionForHR(r);
                if (bc == null)
                {
                    throw new Win32Exception();
                }
                bc.GetRunningObjectTable(out rot);
                if (rot == null)
                {
                    throw new Win32Exception();
                }

                rot.EnumRunning(out enumMoniker);
                if (enumMoniker == null)
                {
                    throw new Win32Exception();
                }

                var cp        = Process.GetCurrentProcess().Id;
                var dteSuffix = ":" + debuggerInfo.ProcessId;

                var moniker = new IMoniker[1];
                while (enumMoniker.Next(1, moniker, IntPtr.Zero) == 0 && moniker[0] != null)
                {
                    string dn;

                    moniker[0].GetDisplayName(bc, null, out dn);

                    if (dn.StartsWith("!VisualStudio.DTE.") && dn.EndsWith(dteSuffix))
                    {
                        object dte, dbg, lps;
                        rot.GetObject(moniker[0], out dte);

                        for (var i = 0; i < 10; i++)
                        {
                            try
                            {
                                dbg = dte.GetType().InvokeMember("Debugger", BindingFlags.GetProperty, null, dte, null);
                                lps = dbg.GetType().InvokeMember("LocalProcesses", BindingFlags.GetProperty, null, dbg, null);
                                var lpn = (System.Collections.IEnumerator)lps.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, lps, null);

                                while (lpn.MoveNext())
                                {
                                    var pn = Convert.ToInt32(lpn.Current.GetType().InvokeMember("ProcessID", BindingFlags.GetProperty, null, lpn.Current, null));

                                    if (pn == cp)
                                    {
                                        lpn.Current.GetType().InvokeMember("Attach", BindingFlags.InvokeMethod, null, lpn.Current, null);
                                        return(true);
                                    }
                                }
                            }
                            catch (COMException)
                            {
                                Thread.Sleep(250);
                            }
                        }
                        Marshal.ReleaseComObject(moniker[0]);

                        break;
                    }

                    Marshal.ReleaseComObject(moniker[0]);
                }
                return(false);
            }
            finally
            {
                if (enumMoniker != null)
                {
                    Marshal.ReleaseComObject(enumMoniker);
                }
                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }
                if (bc != null)
                {
                    Marshal.ReleaseComObject(bc);
                }
            }
        }
        /// <summary>
        /// Program initialization
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event arguments</param>
        private void OnLoad(object sender, EventArgs e)
        {
            // program title
            Text = "Pdf417VideoDecoder - " + Pdf417Decoder.VersionNumber + " \u00a9 2019 Uzi Granot. All rights reserved.";

                #if DEBUG
            // current directory
            string CurDir  = Environment.CurrentDirectory;
            string WorkDir = CurDir.Replace("bin\\Debug", "Work");
            if (WorkDir != CurDir && Directory.Exists(WorkDir))
            {
                Environment.CurrentDirectory = WorkDir;
            }

            // open trace file
            Pdf417Trace.Open("Pdf417VideoDecoderTrace.txt");
            Pdf417Trace.Write(Text);
                #endif

            // disable reset button
            ResetButton.Enabled   = false;
            GoToUriButton.Enabled = false;

            // get an array of web camera devices
            DsDevice[] CameraDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);

            // make sure at least one is available
            if (CameraDevices == null || CameraDevices.Length == 0)
            {
                MessageBox.Show("No video cameras in this computer");
                Close();
                return;
            }

            // select the first camera
            DsDevice CameraDevice = CameraDevices[0];

            // Device moniker
            IMoniker CameraMoniker = CameraDevice.Moniker;

            // get a list of frame sizes available
            FrameSize[] FrameSizes = Camera.GetFrameSizeList(CameraMoniker);

            // make sure there is at least one frame size
            if (FrameSizes == null || FrameSizes.Length == 0)
            {
                MessageBox.Show("No video cameras in this computer");
                Close();
                return;
            }

            // test if our frame size is available
            int Index;
            for (Index = 0; Index < FrameSizes.Length &&
                 (FrameSizes[Index].Width != FrameSize.Width || FrameSizes[Index].Height != FrameSize.Height); Index++)
            {
                ;
            }

            // select first frame size
            if (Index == FrameSizes.Length)
            {
                FrameSize = FrameSizes[0];
            }

            // Set selected camera to camera control with default frame size
            // Create camera object
            VideoCamera = new Camera(PreviewPanel, CameraMoniker, FrameSize);

            // create QR code decoder
            Decoder = new Pdf417Decoder();

            // resize window
            OnResize(sender, e);

            // create timer
            VideoDecoderTimer          = new Timer();
            VideoDecoderTimer.Interval = 200;
            VideoDecoderTimer.Tick    += VideoDecoderTimer_Tick;
            VideoDecoderTimer.Enabled  = true;
            return;
        }
示例#48
0
        private static DTE GetDTE(int processId)
        {
            MessageFilter.Register();

            var prefix = Process.GetProcessById(processId).ProcessName;

            if ("devenv".Equals(prefix, StringComparison.OrdinalIgnoreCase))
            {
                prefix = "VisualStudio";
            }

            string progId        = string.Format("!{0}.DTE.{1}:{2}", prefix, AssemblyVersionInfo.VSVersion, processId);
            object runningObject = null;

            IBindCtx            bindCtx      = null;
            IRunningObjectTable rot          = null;
            IEnumMoniker        enumMonikers = null;

            try {
                Marshal.ThrowExceptionForHR(CreateBindCtx(reserved: 0, ppbc: out bindCtx));
                bindCtx.GetRunningObjectTable(out rot);
                rot.EnumRunning(out enumMonikers);

                IMoniker[] moniker       = new IMoniker[1];
                uint       numberFetched = 0;
                while (enumMonikers.Next(1, moniker, out numberFetched) == 0)
                {
                    IMoniker runningObjectMoniker = moniker[0];

                    string name = null;

                    try {
                        if (runningObjectMoniker != null)
                        {
                            runningObjectMoniker.GetDisplayName(bindCtx, null, out name);
                        }
                    } catch (UnauthorizedAccessException) {
                        // Do nothing, there is something in the ROT that we do not have access to.
                    }

                    if (!string.IsNullOrEmpty(name) && string.Equals(name, progId, StringComparison.Ordinal))
                    {
                        rot.GetObject(runningObjectMoniker, out runningObject);
                        break;
                    }
                }
            } finally {
                if (enumMonikers != null)
                {
                    Marshal.ReleaseComObject(enumMonikers);
                }

                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }

                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }

            return((DTE)runningObject);
        }
示例#49
0
 public static extern int MkParseDisplayName(IBindCtx pbc, string szUserName, ref int pchEaten, out IMoniker ppmk);
示例#50
0
        internal static DTE2 GetDTE()
        {
            string progId        = @"^!VisualStudio\.DTE\.\d{2}\.\d\:" + System.Diagnostics.Process.GetCurrentProcess().Id + "$";
            object runningObject = null;

            IBindCtx            bindCtx      = null;
            IRunningObjectTable rot          = null;
            IEnumMoniker        enumMonikers = null;

            try
            {
                Marshal.ThrowExceptionForHR(CreateBindCtx(reserved: 0, ppbc: out bindCtx));
                bindCtx.GetRunningObjectTable(out rot);
                rot.EnumRunning(out enumMonikers);

                IMoniker[] moniker       = new IMoniker[1];
                IntPtr     numberFetched = IntPtr.Zero;
                while (enumMonikers.Next(1, moniker, numberFetched) == 0)
                {
                    IMoniker runningObjectMoniker = moniker[0];

                    string name = null;

                    try
                    {
                        if (runningObjectMoniker != null)
                        {
                            runningObjectMoniker.GetDisplayName(bindCtx, null, out name);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // Do nothing, there is something in the ROT that we do not have access to.
                    }

                    if (!string.IsNullOrEmpty(name) && Regex.IsMatch(name, progId))
                    {
                        Marshal.ThrowExceptionForHR(rot.GetObject(runningObjectMoniker, out runningObject));
                        break;
                    }
                }
            }
            finally
            {
                if (enumMonikers != null)
                {
                    Marshal.ReleaseComObject(enumMonikers);
                }

                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }

                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }

            return((DTE2)runningObject);
        }
示例#51
0
 public void OnRename(IMoniker pmk)
 {
 }
示例#52
0
        /// <summary>
        /// Create an instance of the filter.
        /// </summary>
        ///
        /// <param name="filterMoniker">Filter's moniker string.</param>
        ///
        /// <returns>Returns filter's object, which implements <b>IBaseFilter</b> interface.</returns>
        ///
        /// <remarks>The returned filter's object should be released using <b>Marshal.ReleaseComObject()</b>.</remarks>
        ///
        public static object CreateFilter(string filterMoniker)
        {
            object         filterObject = null;
            object         comObj       = null;
            ICreateDevEnum enumDev      = null;
            IEnumMoniker   enumMon      = null;

            IMoniker[] devMon = new IMoniker[1];
            int        hr;

            try
            {
                // Get the system device enumerator
                Type srvType = Type.GetTypeFromCLSID(Clsid.SystemDeviceEnum);
                if (srvType == null)
                {
                    throw new ApplicationException("Failed creating device enumerator");
                }

                // create device enumerator
                comObj  = Activator.CreateInstance(srvType);
                enumDev = (ICreateDevEnum)comObj;

                // Create an enumerator to find filters of specified category

                Guid cat = FilterCategory.VideoInputDevice;
                hr = enumDev.CreateClassEnumerator(ref cat, out enumMon, 0);
                if (hr != 0)
                {
                    throw new ApplicationException("No devices of the category");
                }

                // Collect all filters
                IntPtr n = IntPtr.Zero;
                while (true)
                {
                    // Get next filter
                    hr = enumMon.Next(1, devMon, n);
                    if ((hr != 0) || (devMon[0] == null))
                    {
                        break;
                    }

                    // Add the filter
                    FilterInfo filter = new FilterInfo(devMon[0]);
                    if (filter.MonikerString == filterMoniker)
                    {
                        Guid filterId = typeof(IBaseFilter).GUID;
                        devMon[0].BindToObject(null, null, ref filterId, out filterObject);
                        break;
                    }

                    // Release COM object
                    Marshal.ReleaseComObject(devMon[0]);
                    devMon[0] = null;
                }
            }
            catch
            {
            }
            finally
            {
                // release all COM objects
                enumDev = null;
                if (comObj != null)
                {
                    Marshal.ReleaseComObject(comObj);
                    comObj = null;
                }
                if (enumMon != null)
                {
                    Marshal.ReleaseComObject(enumMon);
                    enumMon = null;
                }
                if (devMon[0] != null)
                {
                    Marshal.ReleaseComObject(devMon[0]);
                    devMon[0] = null;
                }
            }
            return(filterObject);
            //// filter's object
            //object filterObject = null;
            //// bind context and moniker objects
            //IBindCtx bindCtx = null;
            //IMoniker moniker = null;

            //int n = 0;

            //// create bind context
            //if ( Win32.CreateBindCtx( 0, out bindCtx ) == 0 )
            //{
            //    // convert moniker`s string to a moniker
            //    if ( Win32.MkParseDisplayName( bindCtx, filterMoniker, ref n, out moniker ) == 0 )
            //    {
            //        // get device base filter
            //        Guid filterId = typeof( IBaseFilter ).GUID;
            //        moniker.BindToObject( null, null, ref filterId, out filterObject );

            //        Marshal.ReleaseComObject( moniker );
            //    }
            //    Marshal.ReleaseComObject( bindCtx );
            //}
            //return filterObject;
        }
示例#53
0
        public RotTableEntry[] DetailedTableAsArray()
        {
            List <RotTableEntry> itemsList = new List <RotTableEntry>();
            IBindCtx             ctx;
            IRunningObjectTable  table;
            IEnumMoniker         mon;

            IMoniker[] lst = new IMoniker[1];
            RotNativeMethods.CreateBindCtx(0, out ctx);
            ctx.GetRunningObjectTable(out table);
            table.EnumRunning(out mon);
            while (mon.Next(1, lst, IntPtr.Zero) == 0)
            {
                RotTableEntry item = new RotTableEntry();
                item.monikerDetails = new MonikerDetails();
                {
                    Guid guid;
                    lst[0].GetClassID(out guid);
                    item.monikerDetails.monikerClassId = RotNativeMethods.StringFromCLSID(guid);
                    switch (item.monikerDetails.monikerClassId)
                    {
                    case "{00000303-0000-0000-C000-000000000046}":
                        item.monikerDetails.monikerType = "FileMoniker";
                        break;

                    case "{00000304-0000-0000-C000-000000000046}":
                        item.monikerDetails.monikerType = "ItemMoniker";
                        break;

                    case "{00000305-0000-0000-C000-000000000046}":
                        item.monikerDetails.monikerType = "AntiMoniker";
                        break;

                    case "{00000306-0000-0000-C000-000000000046}":
                        item.monikerDetails.monikerType = "PointerMoniker";
                        break;

                    case "{00000308-0000-0000-C000-000000000046}":
                        item.monikerDetails.monikerType = "PackageMoniker";
                        break;

                    case "{00000309-0000-0000-C000-000000000046}":
                        item.monikerDetails.monikerType = "CompositeMoniker";
                        break;

                    case "{0000031A-0000-0000-C000-000000000046}":
                        item.monikerDetails.monikerType = "ClassMoniker";
                        break;

                    default:
                    {
                        RegistryKey monikerClassKey = Registry.ClassesRoot.OpenSubKey("CLSID\\" + item.monikerDetails.monikerClassId);
                        if (monikerClassKey == null)
                        {
                            item.monikerDetails.monikerType = "Failed to identify moniker";
                        }
                        else
                        {
                            item.monikerDetails.monikerType = monikerClassKey.GetValue(null).ToString();
                        }
                    }
                    break;
                    }
                }
                {
                    string displayName;
                    lst[0].GetDisplayName(ctx, lst[0], out displayName);
                    item.displayName = displayName;
                    item.className   = "";
                }
                {
                    if (item.monikerDetails.monikerType == "FileMoniker")
                    {
                        System.Runtime.InteropServices.ComTypes.FILETIME ft;
                        table.GetTimeOfLastChange(lst[0], out ft);
                        long     hFT2 = (((long)ft.dwHighDateTime) << 32) + ft.dwLowDateTime;
                        DateTime dte  = DateTime.FromFileTime(hFT2);
                        item.lastChange = dte;
                        //http://snipplr.com/view/32409/
                    }
                    if (item.monikerDetails.monikerType == "ItemMoniker")
                    {
                        string coreGuid = "";
                        {
                            if (item.displayName.Substring(0, 1) == "!")
                            {
                                coreGuid = item.displayName.Substring(1, 38);
                                RegistryKey key = null;
                                key = Registry.ClassesRoot.OpenSubKey("CLSID\\" + coreGuid);
                                if (key == null)
                                {
                                    key = Registry.ClassesRoot.OpenSubKey("Wow6432Node\\CLSID\\" + coreGuid);
                                }
                                if (key != null)
                                {
                                    item.className = key.GetValue(null).ToString();
                                }
                            }
                        }
                    }
                }
                itemsList.Add(item);
            }
            return(itemsList.ToArray());
        }
示例#54
0
        private static DTE GetDTE(int processId)
        {
            // VS 2017 doesn't install some assemblies to the GAC that are needed to work with the
            // debugger, and as the tests don't execute in the devenv.exe process, those assemblies
            // fail to load - so load them manually from PublicAssemblies.

            // Use the executable name, as this is only needed for the out of proc test execution
            // that may interact with the debugger (vstest.executionengine.x86.exe).
            if (!DTELoaded)
            {
                var currentProc = Process.GetCurrentProcess().MainModule.FileName;
                if (StringComparer.OrdinalIgnoreCase.Equals(
                        Path.GetFileName(currentProc), "vstest.executionengine.x86.exe"))
                {
                    var baseDir          = Path.GetDirectoryName(currentProc);
                    var publicAssemblies = Path.Combine(baseDir, "..\\..\\..\\PublicAssemblies");

                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "Microsoft.VisualStudio.OLE.Interop.dll"));
                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "envdte90.dll"));
                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "envdte80.dll"));
                    Assembly.LoadFrom(Path.Combine(publicAssemblies, "envdte.dll"));
                }
                DTELoaded = true;
            }

            MessageFilter.Register();

            var prefix = Process.GetProcessById(processId).ProcessName;

            if ("devenv".Equals(prefix, StringComparison.OrdinalIgnoreCase))
            {
                prefix = "VisualStudio";
            }

            var    progId        = $"!{prefix}.DTE.15.0:{processId}";
            object runningObject = null;

            IBindCtx            bindCtx      = null;
            IRunningObjectTable rot          = null;
            IEnumMoniker        enumMonikers = null;

            try
            {
                Marshal.ThrowExceptionForHR(CreateBindCtx(reserved: 0, ppbc: out bindCtx));
                bindCtx.GetRunningObjectTable(out rot);
                rot.EnumRunning(out enumMonikers);

                var  moniker       = new IMoniker[1];
                uint numberFetched = 0;
                while (enumMonikers.Next(1, moniker, out numberFetched) == 0)
                {
                    var    runningObjectMoniker = moniker[0];
                    string name = null;

                    try
                    {
                        if (runningObjectMoniker != null)
                        {
                            runningObjectMoniker.GetDisplayName(bindCtx, null, out name);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // Do nothing, there is something in the ROT that we do not have access to.
                    }

                    if (StringComparer.Ordinal.Equals(name, progId))
                    {
                        rot.GetObject(runningObjectMoniker, out runningObject);
                        break;
                    }
                }
            }
            finally
            {
                if (enumMonikers != null)
                {
                    Marshal.ReleaseComObject(enumMonikers);
                }

                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }

                if (bindCtx != null)
                {
                    Marshal.ReleaseComObject(bindCtx);
                }
            }

            return((DTE)runningObject);
        }
示例#55
0
        private static ISldWorks GetSwAppFromProcess(int processId)
        {
            var monikerName = "SolidWorks_PID_" + processId.ToString();

            IBindCtx            context  = null;
            IRunningObjectTable rot      = null;
            IEnumMoniker        monikers = null;

            try
            {
                CreateBindCtx(0, out context);

                context.GetRunningObjectTable(out rot);
                rot.EnumRunning(out monikers);

                var moniker = new IMoniker[1];

                while (monikers.Next(1, moniker, IntPtr.Zero) == 0)
                {
                    var curMoniker = moniker.First();

                    string name = null;

                    if (curMoniker != null)
                    {
                        try
                        {
                            curMoniker.GetDisplayName(context, null, out name);
                        }
                        catch (UnauthorizedAccessException)
                        {
                        }
                    }

                    if (string.Equals(monikerName,
                                      name, StringComparison.CurrentCultureIgnoreCase))
                    {
                        object app;
                        rot.GetObject(curMoniker, out app);
                        return(app as ISldWorks);
                    }
                }
            }
            finally
            {
                if (monikers != null)
                {
                    Marshal.ReleaseComObject(monikers);
                }

                if (rot != null)
                {
                    Marshal.ReleaseComObject(rot);
                }

                if (context != null)
                {
                    Marshal.ReleaseComObject(context);
                }
            }

            return(null);
        }
        private void CollectFilters(Guid category)
        {
            object         comObj  = null;
            ICreateDevEnum enumDev = null;
            IEnumMoniker   enumMon = null;

            IMoniker[] devMon = new IMoniker[1];
            int        hr;

            try
            {
                Type srvType = Type.GetTypeFromCLSID(Clsid.SystemDeviceEnum);
                if (srvType == null)
                {
                    throw new ApplicationException("Failed creating device enumerator");
                }


                comObj  = Activator.CreateInstance(srvType);
                enumDev = (ICreateDevEnum)comObj;


                hr = enumDev.CreateClassEnumerator(ref category, out enumMon, 0);
                if (hr != 0)
                {
                    throw new ApplicationException("No devices of the category");
                }


                IntPtr n = IntPtr.Zero;
                while (true)
                {
                    hr = enumMon.Next(1, devMon, n);
                    if ((hr != 0) || (devMon[0] == null))
                    {
                        break;
                    }


                    FilterInfo filter = new FilterInfo(devMon[0]);
                    InnerList.Add(filter);


                    Marshal.ReleaseComObject(devMon[0]);
                    devMon[0] = null;
                }


                InnerList.Sort( );
            }
            catch
            {
            }
            finally
            {
                enumDev = null;
                if (comObj != null)
                {
                    Marshal.ReleaseComObject(comObj);
                    comObj = null;
                }
                if (enumMon != null)
                {
                    Marshal.ReleaseComObject(enumMon);
                    enumMon = null;
                }
                if (devMon[0] != null)
                {
                    Marshal.ReleaseComObject(devMon[0]);
                    devMon[0] = null;
                }
            }
        }
示例#57
0
 public CompressorMoniker(IMoniker mon) : base(mon)
 {
     Console.WriteLine("name: " + name);
 }
示例#58
0
 public Moniker(IMoniker mon)
 {
     this.core = mon;
 }
示例#59
0
    /// <summary>
    /// Gets the DTE object from any devenv process.
    /// </summary>
    /// <param name="processId">
    /// <returns>
    /// Retrieved DTE object or <see langword="null"> if not found.
    /// </see></returns>
    private static DTE2 GetDTE(int processId)
    {
        object runningObject = null;

        IBindCtx            bindCtx      = null;
        IRunningObjectTable rot          = null;
        IEnumMoniker        enumMonikers = null;

        try
        {
            Marshal.ThrowExceptionForHR(CreateBindCtx(reserved: 0, ppbc: out bindCtx));
            bindCtx.GetRunningObjectTable(out rot);
            rot.EnumRunning(out enumMonikers);

            IMoniker[] moniker       = new IMoniker[1];
            IntPtr     numberFetched = IntPtr.Zero;
            while (enumMonikers.Next(1, moniker, numberFetched) == 0)
            {
                IMoniker runningObjectMoniker = moniker[0];

                string name = null;

                try
                {
                    if (runningObjectMoniker != null)
                    {
                        runningObjectMoniker.GetDisplayName(bindCtx, null, out name);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    // Do nothing, there is something in the ROT that we do not have access to.
                }

                Regex monikerRegex = new Regex(@"!VisualStudio.DTE\.\d+\.\d+\:" + processId, RegexOptions.IgnoreCase);
                if (!string.IsNullOrEmpty(name) && monikerRegex.IsMatch(name))
                {
                    Marshal.ThrowExceptionForHR(rot.GetObject(runningObjectMoniker, out runningObject));
                    break;
                }
            }
        }
        finally
        {
            if (enumMonikers != null)
            {
                Marshal.ReleaseComObject(enumMonikers);
            }

            if (rot != null)
            {
                Marshal.ReleaseComObject(rot);
            }

            if (bindCtx != null)
            {
                Marshal.ReleaseComObject(bindCtx);
            }
        }

        return(runningObject as DTE2);
    }
示例#60
0
 private static extern int CoCreateInstance(
     ref Guid clsid, IntPtr outerUnknown, int context, ref Guid iid, out IMoniker ptr);