예제 #1
1
파일: Windows.cs 프로젝트: labeuze/source
 public static WindowInfo[] GetThreadWindowsInfoList(int threadId)
 {
     EnumWindows enumWindows = new EnumWindows();
     return (from hWnd in enumWindows.GetThreadWindowsList(threadId) select GetWindowInfo(hWnd)).ToArray();
 }
예제 #2
0
        /// <summary>
        /// Gets a list of active windows sorted on the
        /// indcated sort order
        /// </summary>
        /// <param name="order">sort order</param>
        /// <returns>sorted list</returns>
        private List <EnumWindows.WindowInfo> getWindowList(SortOrder order)
        {
            var processName = FilterByProcessName.Trim();

            var windowList = EnumWindows.Enumerate();

            if (!String.IsNullOrEmpty(processName))
            {
                var filteredList = new List <EnumWindows.WindowInfo>();

                for (int ii = 0; ii < windowList.Count; ii++)
                {
                    var process = WindowActivityMonitor.GetProcessForWindow(windowList[ii].Handle);
                    if (String.Compare(process.ProcessName, FilterByProcessName, true) == 0)
                    {
                        filteredList.Add(windowList[ii]);
                    }
                }

                windowList = filteredList;
            }

            var sortedList = sortWindowList(windowList, order);

            if (String.IsNullOrEmpty(processName))
            {
                IntPtr desktopHWnd = User32Interop.GetDesktopWindow();
                if (desktopHWnd != null)
                {
                    sortedList.Insert(0, new EnumWindows.WindowInfo(desktopHWnd, R.GetString("ShowDesktop")));
                }
            }

            return(sortedList);
        }
예제 #3
0
 /// <summary>
 /// Form has been loaded
 /// </summary>
 private void WindowMoveResizeScannerForm_Load(object sender, EventArgs e)
 {
     _dialogCommon.OnLoad();
     EnumWindows.RestoreFocusToTopWindow(Handle.ToInt32());
     setMoveResizeMode();
     PanelCommon.AnimationManager.Start(PanelCommon.RootWidget);
 }
예제 #4
0
파일: Windows.cs 프로젝트: 24/source_04
        public static WindowInfo[] GetWindowsInfoListByClassName(string className)
        {
            EnumWindows enumWindows = new EnumWindows();

            enumWindows.ClassNameFilter = className;
            //return (from hWnd in enumWindows.GetWindowsList() where GetWindowClassName(hWnd) == className select GetWindowInfo(hWnd)).ToArray();
            return((from hWnd in enumWindows.GetWindowsList() select GetWindowInfo(hWnd)).ToArray());
        }
예제 #5
0
파일: Windows.cs 프로젝트: 24/source_04
        public static WindowInfo[] GetWindowsInfoList(string title, string className)
        {
            EnumWindows enumWindows = new EnumWindows();

            enumWindows.TitleFilter     = title;
            enumWindows.ClassNameFilter = className;
            return((from hWnd in enumWindows.GetWindowsList() select GetWindowInfo(hWnd)).ToArray());
        }
예제 #6
0
        /// <summary>
        /// Activates a functional agent. The caller should to an 'await'
        /// on this to wait for it to complete.  This is because some
        /// functional agents return data and the caller has to wait
        /// for the functional agent to exit so it can get the data. Eg
        /// FileBrowser agent that returns a filename
        /// </summary>
        /// <param name="caller">The calling agent (can be null)</param>
        /// <param name="agent">Functional agent to activate</param>
        /// <returns>the task to wait on</returns>
        public async Task ActivateAgent(IApplicationAgent caller, IFunctionalAgent agent)
        {
            lock (_syncActivateAgent)
            {
                if (_currentAgent != null && _currentAgent != agent)
                {
                    if (caller == null && !_currentAgent.QueryAgentSwitch(agent))
                    {
                        return;
                    }

                    _currentAgent.OnFocusLost();
                }

                if (caller != null)
                {
                    agent.Parent = caller;
                    caller.OnPause();
                }

                _textControlAgent = agent.TextControlAgent;

                setAgent(agent);
            }

            Log.Debug("Calling activateAgent: " + agent.Name);
            await activateAgent(agent);

            CompletionCode exitCode = agent.ExitCode;

            Log.Debug("Returned from activateAgent: " + agent.Name);
            setAgent(null);

            if (agent.ExitCommand != null)
            {
                if (agent.ExitCommand.ContextSwitch)
                {
                    Context.AppPanelManager.CloseCurrentPanel();
                }

                RunCommandDispatcher.Dispatch(agent.ExitCommand.Command);
            }
            else if (exitCode == CompletionCode.ContextSwitch)
            {
                Context.AppPanelManager.CloseCurrentPanel();
                EnumWindows.RestoreFocusToTopWindow();
                WindowActivityMonitor.GetActiveWindow();
            }
            else
            {
                PausePanelChangeRequests();
                EnumWindows.RestoreFocusToTopWindow();
                ResumePanelChangeRequests(false);
            }
        }
예제 #7
0
        /// <summary>
        /// Attaches a file to the current email being composed.  The currently
        /// focused window has to be the mail compose window.  Sends a
        /// Ctrl+H command to.  Launches the file browser to get the file to attach
        /// from the user.  Then inserts the filename into the attachment field
        /// in the mail compose window
        /// </summary>
        protected async void attachFile()
        {
            var info = WindowActivityMonitor.GetForegroundWindowInfo();

            if (!isMailComposeMessageWindow(info.FocusedElement) &&
                !isMailComposeWindow(info.FocusedElement))
            {
                Log.Debug("Wrong window");
                return;
            }

            _fileAttachment = String.Empty;
            await getFileToAttach();

            if (String.IsNullOrEmpty(_fileAttachment))
            {
                return;
            }

            Thread.Sleep(500);
            EnumWindows.RestoreFocusToTopWindow();
            Thread.Sleep(500);

            SendKeys.SendWait("^h");
            Thread.Sleep(1000);

            for (int ii = 0; ii < 10; ii++)
            {
                var info1 = WindowActivityMonitor.GetForegroundWindowInfo();
                if (info1.Title == "Attach File")
                {
                    Log.Debug("YES!  Found Attach file window");
                    var automationElement = AgentUtils.GetElementOrAncestorByAutomationId(
                        info1.FocusedElement,
                        "Edit",
                        "ControlType.Edit",
                        "1148");
                    if (automationElement != null)
                    {
                        Log.Debug("element is not null");
                        AgentUtils.InsertTextIntoElement(automationElement, _fileAttachment);
                        SendKeys.Send("{ENTER}");
                    }
                    else
                    {
                        Log.Debug("element is null");
                    }

                    break;
                }

                Thread.Sleep(500);
            }
        }
예제 #8
0
파일: Windows.cs 프로젝트: 24/source_04
        public static WindowInfo[] GetProcessWindowsInfoListByClassName(Process process, string className)
        {
            List <IntPtr> windowsList = new List <IntPtr>();
            EnumWindows   enumWindows = new EnumWindows();

            foreach (ProcessThread thread in process.Threads)
            {
                windowsList.AddRange(from hWnd in enumWindows.GetThreadWindowsList(thread.Id) where GetWindowClassName(hWnd) == className select hWnd);
            }
            return((from hWnd in windowsList select GetWindowInfo(hWnd)).ToArray());
        }
예제 #9
0
        private List <string> ShowDesktopWindows()
        {
            List <IntPtr> handles;
            List <string> titles;

            EnumWindows.GetDesktopWindowHandlesAndTitles(out handles, out titles);

            titles.ForEach(v =>
            {
                Trace.WriteLine(v);
            });

            return(titles);
        }
예제 #10
0
        /// <summary>
        /// Attaches a file to the current email being composed.
        /// Launches the file browser to get the file to attach  from the user.
        /// Sends a command to bring up the Outlook "Insert File" dialog.
        /// Inserts the filename into the file name field in the dialog
        /// </summary>
        protected async void attachFile()
        {
            _fileAttachment = String.Empty;
            await getFileToAttach();

            if (String.IsNullOrEmpty(_fileAttachment))
            {
                return;
            }

            Thread.Sleep(500);
            EnumWindows.RestoreFocusToTopWindowOnDesktop();
            Thread.Sleep(500);

            AgentManager.Instance.Keyboard.Send(Keys.F10);
            AgentManager.Instance.Keyboard.Send(Keys.H);
            AgentManager.Instance.Keyboard.Send(Keys.A);
            AgentManager.Instance.Keyboard.Send(Keys.F);

            Thread.Sleep(1000);

            for (int ii = 0; ii < 10; ii++)
            {
                var info1 = WindowActivityMonitor.GetForegroundWindowInfo();
                if (String.Compare(info1.Title, R.GetString2("OutlookAttachFileWindowTitle"), true) == 0)
                {
                    Log.Debug("YES!  Found Attach file window");
                    var automationElement = AgentUtils.GetElementOrAncestorByAutomationId(
                        info1.FocusedElement,
                        "Edit",
                        "ControlType.Edit",
                        "1148");
                    if (automationElement != null)
                    {
                        Log.Debug("element is not null");
                        AgentUtils.InsertTextIntoElement(automationElement, _fileAttachment);
                        SendKeys.Send("{ENTER}");
                    }
                    else
                    {
                        Log.Debug("element is null");
                    }

                    break;
                }

                Thread.Sleep(500);
            }
        }
예제 #11
0
        /// <summary>
        /// Form has been loaded
        /// </summary>
        private void TaskSwitcherForm_Load(object sender, EventArgs e)
        {
            Log.Debug();

            dtlp.Show();

            _dialogCommon.OnLoad();
            subscribeToEvents();

            var windowList = EnumWindows.Enumerate();

            if (!String.IsNullOrEmpty(FilterProcessName))
            {
                List <EnumWindows.WindowInfo> filteredList = new List <EnumWindows.WindowInfo>();

                for (int ii = 0; ii < windowList.Count; ii++)
                {
                    Process process = WindowActivityMonitor.GetProcessForWindow(windowList[ii].Handle);
                    if (String.Compare(process.ProcessName, FilterProcessName, true) == 0)
                    {
                        filteredList.Add(windowList[ii]);
                    }
                }

                windowList = filteredList;
            }
            else
            {
                Log.Debug("list count=" + windowList.Count);

                IntPtr desktopHWnd = User32Interop.GetDesktopWindow();

                Log.Debug("desktopHWnd=" + desktopHWnd.ToString());

                if (desktopHWnd != null)
                {
                    windowList.Insert(0, new EnumWindows.WindowInfo(desktopHWnd, "Show Desktop"));
                }
            }

            PopulateTLP(windowList);

            Windows.SetWindowPosition(this, Windows.WindowPosition.CenterScreen);

            _dialogCommon.GetAnimationManager().Start(_dialogCommon.GetRootWidget());
            Log.Debug("returning");
        }
예제 #12
0
파일: Windows.cs 프로젝트: 24/source_04
        public static WindowInfo[] GetProcessWindowsInfoList(Process process, bool mainWindow)
        {
            List <IntPtr> windowsList = new List <IntPtr>();
            EnumWindows   enumWindows = new EnumWindows();

            foreach (ProcessThread thread in process.Threads)
            {
                if (mainWindow)
                {
                    windowsList.AddRange(from hWnd in enumWindows.GetThreadWindowsList(thread.Id) where User.GetParent(hWnd) == IntPtr.Zero select hWnd);
                }
                else
                {
                    windowsList.AddRange(enumWindows.GetThreadWindowsList(thread.Id));
                }
            }
            return((from hWnd in windowsList select GetWindowInfo(hWnd)).ToArray());
        }
예제 #13
0
        private void WindowCreated(object sender, WindowEventArgs e)
        {
            if (e.Handle != IntPtr.Zero && new SystemMenu(e.Handle, _settings.MenuItems).Exists&& !_windows.Any(w => w.Handle == e.Handle))
            {
                int processId;
                NativeMethods.GetWindowThreadProcessId(e.Handle, out processId);
                IList <Window> windows = new List <Window>();
                try
                {
                    windows = EnumWindows.EnumProcessWindows(processId, _windows.Select(w => w.Handle).ToArray(), _settings.MenuItems, new string[] { SHELL_WINDOW_NAME });
                }
                catch
                {
                }

                foreach (var window in windows)
                {
                    var processName = "";

                    try
                    {
                        processName = Path.GetFileName(window.Process.GetMainModuleFileName());
                    }
                    catch
                    {
                    }

                    if (string.IsNullOrEmpty(processName) || _settings.ProcessExclusions.Contains(processName.ToLower()))
                    {
                        continue;
                    }

                    window.Menu.Create();
                    int menuItemId = window.ProcessPriority.GetMenuItemId();
                    window.Menu.CheckMenuItem(menuItemId, true);
                    window.Menu.SetMenuItemText(SystemMenu.SC_ALIGN_MONITOR, "Select Monitor: " + Screen.AllScreens.ToList().FindIndex(s => s.Primary));
                    if (window.AlwaysOnTop)
                    {
                        window.Menu.CheckMenuItem(SystemMenu.SC_TOPMOST, true);
                    }
                    _windows.Add(window);
                }
            }
        }
예제 #14
0
        /// <summary>
        /// Invoked when the selects a window in the switch windows scanner.
        /// Set focus to the selected window and quit the agent.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="windowInfo"></param>
        private void _switchWindowsScanner_EvtActivateWindow(object sender, EnumWindows.WindowInfo windowInfo)
        {
            _windowInfo = windowInfo;

            IsClosing = true;
            IsActive  = false;

            if (Windows.IsDesktopWindow(_windowInfo.Handle))
            {
                Context.AppAgentMgr.Keyboard.Send(Keys.LWin, Keys.D);
            }
            else
            {
                Windows.ActivateWindow(_windowInfo.Handle);
                EnumWindows.RestoreFocusToTopWindowOnDesktop();
            }

            closeScanner();
            Close();
        }
예제 #15
0
        /// <summary>
        /// Talk window form closed. Notify subscribers and
        /// restore focus to the application window that at
        /// the top of the Z order
        /// </summary>
        /// <param name="sender">event sender</param>
        /// <param name="e">event args</param>
        private void _talkWindowForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Log.Debug("********* Calling EXiting all frames");
            System.Windows.Threading.Dispatcher.ExitAllFrames();
            System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvokeShutdown(System.Windows.Threading.DispatcherPriority.Background);

            Log.Debug("appquit: " + PanelManagement.Context.AppQuit);

            if (!PanelManagement.Context.AppQuit)
            {
                if (EvtTalkWindowClosed != null)
                {
                    EvtTalkWindowClosed(this, new EventArgs());
                }

                EnumWindows.RestoreFocusToTopWindow();
                WindowActivityMonitor.GetActiveWindowAsync();
            }

            Log.Debug("Exiting");
        }
예제 #16
0
        private void RefreshWindows()
        {
            Utility.Log("Enumerating windows.");
            var handles        = EnumWindows.GetAllHandles();
            var managedHandles = _windowsByHandle.Keys.ToArray();

            foreach (var newHandle in handles.Except(managedHandles))
            {
                var newWindow = new TopazWindow(newHandle);
                _windowsByHandle.Add(newHandle, newWindow);
            }

            foreach (var removedHandle in managedHandles.Except(handles))
            {
                _windowsByHandle.Remove(removedHandle);
            }

            Utility.Log("Added", handles.Except(managedHandles).Count(), "windows.");
            Utility.Log("Removed", managedHandles.Except(handles).Count(), "windows.");
            Utility.Log("Tracking", _windowsByHandle.Count, "windows.");

            UpdateWorkspaceWindows(Workspaces.First(w => w.Display == Screen.PrimaryScreen && w.Desktop == VirtualDesktop.Current));
        }
예제 #17
0
        /// <summary>
        /// Talk window form closed. Notify subscribers and
        /// restore focus to the application window that at
        /// the top of the Z order
        /// </summary>
        /// <param name="sender">event sender</param>
        /// <param name="e">event args</param>
        private void _talkWindowForm_FormClosed(object sender, FormClosedEventArgs e)
        {
#if TALKWINDOW_DISPATCHER_THREAD

            Log.Debug("********* Calling EXiting all frames");
            System.Windows.Threading.Dispatcher.ExitAllFrames();
            System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvokeShutdown(System.Windows.Threading.DispatcherPriority.Background);
#endif
            Log.Debug("appquit: " + Context.AppQuit);

            if (!Context.AppQuit)
            {
                if (EvtTalkWindowClosed != null)
                {
                    EvtTalkWindowClosed(this, new EventArgs());
                }

                //Context.AppPanelManager.CloseCurrentForm();
                EnumWindows.RestoreFocusToTopWindowOnDesktop();
                WindowActivityMonitor.GetActiveWindowAsync();
            }

            Log.Debug("Exiting");
        }
예제 #18
0
파일: Windows.cs 프로젝트: labeuze/source
 public static IntPtr[] GetDesktopWindowsList(IntPtr hDesktop)
 {
     EnumWindows enumWindows = new EnumWindows();
     return enumWindows.GetDesktopWindowsList(hDesktop).ToArray();
 }
예제 #19
0
파일: Windows.cs 프로젝트: labeuze/source
 public static IntPtr[] GetChildWindowsList(IntPtr hwndParent)
 {
     EnumWindows enumWindows = new EnumWindows();
     return enumWindows.GetChildWindowsList(hwndParent).ToArray();
 }
예제 #20
0
파일: Windows.cs 프로젝트: labeuze/source
 public static WindowInfo[] GetChildWindowsInfoList(IntPtr hwndParent)
 {
     EnumWindows enumWindows = new EnumWindows();
     return (from hWnd in enumWindows.GetChildWindowsList(hwndParent) select GetWindowInfo(hWnd)).ToArray();
 }
예제 #21
0
파일: Windows.cs 프로젝트: labeuze/source
 public static WindowInfo[] GetWindowsInfoList(string title, string className)
 {
     EnumWindows enumWindows = new EnumWindows();
     enumWindows.TitleFilter = title;
     enumWindows.ClassNameFilter = className;
     return (from hWnd in enumWindows.GetWindowsList() select GetWindowInfo(hWnd)).ToArray();
 }
예제 #22
0
파일: Windows.cs 프로젝트: labeuze/source
 public static WindowInfo[] GetWindowsInfoListByClassName(string className)
 {
     EnumWindows enumWindows = new EnumWindows();
     enumWindows.ClassNameFilter = className;
     //return (from hWnd in enumWindows.GetWindowsList() where GetWindowClassName(hWnd) == className select GetWindowInfo(hWnd)).ToArray();
     return (from hWnd in enumWindows.GetWindowsList() select GetWindowInfo(hWnd)).ToArray();
 }
예제 #23
0
        private void PopulateTLP(List <EnumWindows.WindowInfo> windowList)
        {
            Log.Debug("Starting to populate table layout panel...");

            int appCount = windowList.Count;

            if (appCount == 0)
            {
                return;
            }

            int columnWidth;

            _widgetList = new List <PictureBoxWidget>();

            // add rows and columns
            dtlp.ColumnCount = NumAppsPerRow;
            dtlp.RowCount    = (int)Math.Ceiling((double)appCount / (double)NumAppsPerRow);

            columnWidth = ColumnWidth;

            dtlp.ColumnStyles.Clear();

            // add each column
            for (int y = 0; y < NumAppsPerRow; y++)
            {
                dtlp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, columnWidth));
            }

            // start adding app icons
            // used to break out of loop once we have processed all the apps

            int i = 0;

            dtlp.RowStyles.Clear();

            for (int x = 0; x < dtlp.RowCount; x++)
            {
                dtlp.RowStyles.Add(new RowStyle(SizeType.Absolute, RowHeight));
            }

            for (int currentRow = 0, index = 0; currentRow < dtlp.RowCount; currentRow++)
            {
                for (int currentColumn = 0; currentColumn < NumAppsPerRow; currentColumn++)
                {
                    PictureBox pbxAppIcon1 = new PictureBox();
                    pbxAppIcon1.Name     = "ListItem" + index++;
                    pbxAppIcon1.SizeMode = PictureBoxSizeMode.CenterImage;

                    PictureBoxWidget pictureBoxWidget = _dialogCommon.GetWidgetManager().Layout.CreateWidget(typeof(PictureBoxWidget), pbxAppIcon1) as PictureBoxWidget;
                    pictureBoxWidget.EvtActuated    += new WidgetEventDelegate(bitmapWidget_EvtActuated);
                    pictureBoxWidget.EvtHighlightOn += new HighlightOnDelegate(bitmapWidget_EvtHighlightOn);

                    Log.Debug("Bitmap widget is " + ((pictureBoxWidget == null) ? "null" : "not null"));

                    TaskData taskData = new TaskData();
                    taskData.Handle = windowList[i].Handle;
                    taskData.Title  = windowList[i].Title;

                    pictureBoxWidget.UserData = taskData;

                    IntPtr handle = windowList[i].Handle;
                    Icon   icon   = EnumWindows.GetAppIcon(handle);

                    if (icon == null)
                    {
                        Log.Debug("No app icon found for hWnd=" + handle.ToString() + " title=" + windowList[i].Title);
                        Log.Debug("Loading default icon");
                        Image img = Image.FromFile(FileUtils.GetImagePath("taskSwitchdefaultIcon.bmp"));
                        if (img != null)
                        {
                            pbxAppIcon1.Image = img;
                        }
                    }
                    else
                    {
                        Log.Debug("Icon found for hWnd=" + handle.ToString() + " icon=" + icon.ToString() + " title=" + windowList[i].Title);
                        pbxAppIcon1.Image = icon.ToBitmap();
                    }

                    pbxAppIcon1.BorderStyle = BorderStyle.None;
                    pbxAppIcon1.Anchor      = AnchorStyles.None;
                    pbxAppIcon1.Dock        = DockStyle.Fill;
                    pbxAppIcon1.SizeMode    = PictureBoxSizeMode.StretchImage;
                    dtlp.Controls.Add(pbxAppIcon1, currentColumn, currentRow);

                    _widgetList.Add(pictureBoxWidget);

                    // TODO: do something else with spare cells
                    if (i < (appCount - 1))
                    {
                        i++;
                    }
                    else
                    {
                        break;
                    }
                }
            }

#if FORCE_FIXED_TABLE_SIZE
            this.Size = new System.Drawing.Size(1000, 1000);
#else
            int newFormWidth  = FormWidthBase + (NumAppsPerRow * ColumnWidth);
            int newFormHeight = 20 + (FormHeightBase + Convert.ToInt32(Math.Ceiling(dtlp.RowCount * RowHeight)));
            Log.Debug("newFormWidth=" + newFormWidth + " newFormHeight=" + newFormHeight);

            _dialogCommon.Resize(new System.Drawing.Size(newFormWidth, newFormHeight));
            onResize();

            Log.Debug("form width=" + this.Size.Width.ToString() + " form height=" + this.Size.Height.ToString());
            Log.Debug("title width=" + Title.Size.Width);
#endif
        }
예제 #24
0
파일: Windows.cs 프로젝트: 24/source_04
        public static WindowInfo[] GetThreadWindowsInfoList(int threadId)
        {
            EnumWindows enumWindows = new EnumWindows();

            return((from hWnd in enumWindows.GetThreadWindowsList(threadId) select GetWindowInfo(hWnd)).ToArray());
        }
예제 #25
0
파일: Windows.cs 프로젝트: labeuze/source
 public static WindowInfo[] GetProcessWindowsInfoListByClassName(Process process, string className)
 {
     List<IntPtr> windowsList = new List<IntPtr>();
     EnumWindows enumWindows = new EnumWindows();
     foreach (ProcessThread thread in process.Threads)
         windowsList.AddRange(from hWnd in enumWindows.GetThreadWindowsList(thread.Id) where GetWindowClassName(hWnd) == className select hWnd);
     return (from hWnd in windowsList select GetWindowInfo(hWnd)).ToArray();
 }
예제 #26
0
파일: Windows.cs 프로젝트: 24/source_04
        public static IntPtr[] GetWindowsList()
        {
            EnumWindows enumWindows = new EnumWindows();

            return(enumWindows.GetWindowsList().ToArray());
        }
예제 #27
0
파일: Windows.cs 프로젝트: labeuze/source
 public static WindowInfo[] GetDesktopWindowsInfoList(IntPtr hDesktop)
 {
     EnumWindows enumWindows = new EnumWindows();
     return (from hWnd in enumWindows.GetDesktopWindowsList(hDesktop) select GetWindowInfo(hWnd)).ToArray();
 }
예제 #28
0
파일: Windows.cs 프로젝트: 24/source_04
        public static IntPtr[] GetDesktopWindowsList(IntPtr hDesktop)
        {
            EnumWindows enumWindows = new EnumWindows();

            return(enumWindows.GetDesktopWindowsList(hDesktop).ToArray());
        }
예제 #29
0
    /// <summary>
    /// Sends the specified object on this channel to any other
    /// applications which are listening.  The object must have the
    /// SerializableAttribute set, or must implement ISerializable.
    /// </summary>
    /// <param name="obj">The object to send</param>
    /// <returns>The number of recipients</returns>
    public int Send(object obj)
    {
        int recipients = 0;

        if (disposed)
        {
            throw new InvalidOperationException("Object has been disposed");
        }

        if (recreateChannel) // handle has changed
        {
            addChannel();
        }

        CopyDataObjectData cdo = new CopyDataObjectData(obj, channelName);

        // Try to do a binary serialization on obj.
        // This will throw and exception if the object to
        // be passed isn't serializable.
        BinaryFormatter b = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();
        b.Serialize(stream, cdo);
        stream.Flush();

        // Now move the data into a pointer so we can send
        // it using WM_COPYDATA:
        // Get the length of the data:
        int dataSize = (int)stream.Length;
        if (dataSize > 0)
        {
            // This isn't very efficient if your data is very large.
            // First we copy to a byte array, then copy to a CoTask
            // Mem object... And when we use WM_COPYDATA windows will
            // make yet another copy!  But if you're talking about 4K
            // or less of data then it doesn't really matter.
            byte[] data = new byte[dataSize];
            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(data, 0, dataSize);
            IntPtr ptrData = Marshal.AllocCoTaskMem(dataSize);
            Marshal.Copy(data, 0, ptrData, dataSize);

            // Enumerate all windows which have the
            // channel name, send the data to each one
            EnumWindows ew = new EnumWindows();
            ew.GetWindows();

            // Send the data to each window identified on
            // the channel:
            foreach(EnumWindowsItem window in ew.Items)
            {
                if (!window.Handle.Equals(this.owner.Handle))
                {
                    if (GetProp(window.Handle, this.channelName) != 0)
                    {
                        COPYDATASTRUCT cds = new COPYDATASTRUCT();
                        cds.cbData = dataSize;
                        cds.dwData = IntPtr.Zero;
                        cds.lpData = ptrData;
                        int res = SendMessage(window.Handle, WM_COPYDATA,
                            (int)owner.Handle, ref cds);
                        recipients += (Marshal.GetLastWin32Error() == 0 ? 1 : 0);
                    }
                }
            }

            // Clear up the data:
            Marshal.FreeCoTaskMem(ptrData);
        }
        stream.Close();

        return recipients;
    }
예제 #30
0
파일: Windows.cs 프로젝트: 24/source_04
        public static WindowInfo[] GetDesktopWindowsInfoList(IntPtr hDesktop)
        {
            EnumWindows enumWindows = new EnumWindows();

            return((from hWnd in enumWindows.GetDesktopWindowsList(hDesktop) select GetWindowInfo(hWnd)).ToArray());
        }
예제 #31
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var settingsFileName = Path.Combine(AssemblyUtils.AssemblyDirectory, "SmartSystemMenu.xml");

            if (File.Exists(settingsFileName))
            {
                _settings = SmartSystemMenuSettings.Read(settingsFileName);
            }
#if WIN32
            if (Environment.Is64BitOperatingSystem)
            {
                string resourceName  = "SmartSystemMenu.SmartSystemMenu64.exe";
                string fileName      = "SmartSystemMenu64.exe";
                string directoryName = Path.GetDirectoryName(AssemblyUtils.AssemblyLocation);
                string filePath      = Path.Combine(directoryName, fileName);
                try
                {
                    if (!File.Exists(filePath))
                    {
                        AssemblyUtils.ExtractFileFromAssembly(resourceName, filePath);
                    }
                    _64BitProcess = Process.Start(filePath);
                }
                catch
                {
                    string message = string.Format("Failed to load {0} process!", fileName);
                    MessageBox.Show(message, AssemblyUtils.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Close();
                    return;
                }
            }
            _systemTrayMenu = new SystemTrayMenu();
            _systemTrayMenu.MenuItemAutoStart.Click  += MenuItemAutoStartClick;
            _systemTrayMenu.MenuItemSettings.Click   += MenuItemSettingsClick;
            _systemTrayMenu.MenuItemAbout.Click      += MenuItemAboutClick;
            _systemTrayMenu.MenuItemExit.Click       += MenuItemExitClick;
            _systemTrayMenu.MenuItemAutoStart.Checked = AutoStarter.IsAutoStartByRegisterEnabled(AssemblyUtils.AssemblyProductName, AssemblyUtils.AssemblyLocation);
#endif
            _windows = EnumWindows.EnumAllWindows(_settings.MenuItems, new string[] { SHELL_WINDOW_NAME }).ToList();

            foreach (var window in _windows)
            {
                var processName = "";

                try
                {
                    processName = Path.GetFileName(window.Process.GetMainModuleFileName());
                }
                catch
                {
                }

                if (string.IsNullOrEmpty(processName) || _settings.ProcessExclusions.Contains(processName.ToLower()))
                {
                    continue;
                }

                window.Menu.Create();
                int menuItemId = window.ProcessPriority.GetMenuItemId();
                window.Menu.CheckMenuItem(menuItemId, true);
                window.Menu.SetMenuItemText(SystemMenu.SC_ALIGN_MONITOR, "Select Monitor: " + Screen.AllScreens.ToList().FindIndex(s => s.Primary));
                if (window.AlwaysOnTop)
                {
                    window.Menu.CheckMenuItem(SystemMenu.SC_TOPMOST, true);
                }
            }

            _getMsgHook         = new GetMsgHook(Handle, SystemMenu.SC_DRAG_BY_MOUSE);
            _getMsgHook.GetMsg += WindowGetMsg;
            _getMsgHook.Start();

            _shellHook = new ShellHook(Handle, SystemMenu.SC_DRAG_BY_MOUSE);
            _shellHook.WindowCreated   += WindowCreated;
            _shellHook.WindowDestroyed += WindowDestroyed;
            _shellHook.Start();

            _cbtHook = new CBTHook(Handle, SystemMenu.SC_DRAG_BY_MOUSE);
            _cbtHook.WindowCreated   += WindowCreated;
            _cbtHook.WindowDestroyed += WindowDestroyed;
            _cbtHook.MoveSize        += WindowMoveSize;
            _cbtHook.MinMax          += WindowMinMax;
            _cbtHook.Start();

            _mouseHook = new MouseHook(Handle, SystemMenu.SC_DRAG_BY_MOUSE);
            _mouseHook.Start();

            Hide();
        }
예제 #32
0
파일: Windows.cs 프로젝트: labeuze/source
 public static WindowInfo[] GetProcessWindowsInfoList(Process process, bool mainWindow)
 {
     List<IntPtr> windowsList = new List<IntPtr>();
     EnumWindows enumWindows = new EnumWindows();
     foreach (ProcessThread thread in process.Threads)
     {
         if (mainWindow)
             windowsList.AddRange(from hWnd in enumWindows.GetThreadWindowsList(thread.Id) where User.GetParent(hWnd) == IntPtr.Zero select hWnd);
         else
             windowsList.AddRange(enumWindows.GetThreadWindowsList(thread.Id));
     }
     return (from hWnd in windowsList select GetWindowInfo(hWnd)).ToArray();
 }
예제 #33
0
파일: Windows.cs 프로젝트: 24/source_04
        public static WindowInfo[] GetChildWindowsInfoList(IntPtr hwndParent)
        {
            EnumWindows enumWindows = new EnumWindows();

            return((from hWnd in enumWindows.GetChildWindowsList(hwndParent) select GetWindowInfo(hWnd)).ToArray());
        }
예제 #34
0
파일: Windows.cs 프로젝트: labeuze/source
 public static IntPtr[] GetThreadWindowsList(int threadId)
 {
     EnumWindows enumWindows = new EnumWindows();
     return enumWindows.GetThreadWindowsList(threadId).ToArray();
 }
예제 #35
0
파일: Windows.cs 프로젝트: 24/source_04
        public static IntPtr[] GetChildWindowsList(IntPtr hwndParent)
        {
            EnumWindows enumWindows = new EnumWindows();

            return(enumWindows.GetChildWindowsList(hwndParent).ToArray());
        }
예제 #36
0
    /// <summary>
    /// Sends the specified object on this channel to any other
    /// applications which are listening.  The object must have the
    /// SerializableAttribute set, or must implement ISerializable.
    /// </summary>
    /// <param name="obj">The object to send</param>
    /// <returns>The number of recipients</returns>
    public int Send(object obj)
    {
        int recipients = 0;

        if (disposed)
        {
            throw new InvalidOperationException("Object has been disposed");
        }

        if (recreateChannel)         // handle has changed
        {
            addChannel();
        }

        CopyDataObjectData cdo = new CopyDataObjectData(obj, channelName);


        // Try to do a binary serialization on obj.
        // This will throw and exception if the object to
        // be passed isn't serializable.
        BinaryFormatter b      = new BinaryFormatter();
        MemoryStream    stream = new MemoryStream();

        b.Serialize(stream, cdo);
        stream.Flush();

        // Now move the data into a pointer so we can send
        // it using WM_COPYDATA:
        // Get the length of the data:
        int dataSize = (int)stream.Length;

        if (dataSize > 0)
        {
            // This isn't very efficient if your data is very large.
            // First we copy to a byte array, then copy to a CoTask
            // Mem object... And when we use WM_COPYDATA windows will
            // make yet another copy!  But if you're talking about 4K
            // or less of data then it doesn't really matter.
            byte[] data = new byte[dataSize];
            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(data, 0, dataSize);
            IntPtr ptrData = Marshal.AllocCoTaskMem(dataSize);
            Marshal.Copy(data, 0, ptrData, dataSize);

            // Enumerate all windows which have the
            // channel name, send the data to each one
            EnumWindows ew = new EnumWindows();
            ew.GetWindows();

            // Send the data to each window identified on
            // the channel:
            foreach (EnumWindowsItem window in ew.Items)
            {
                if (!window.Handle.Equals(this.owner.Handle))
                {
                    if (GetProp(window.Handle, this.channelName) != 0)
                    {
                        COPYDATASTRUCT cds = new COPYDATASTRUCT();
                        cds.cbData = dataSize;
                        cds.dwData = IntPtr.Zero;
                        cds.lpData = ptrData;
                        int res = SendMessage(window.Handle, WM_COPYDATA,
                                              (int)owner.Handle, ref cds);
                        recipients += (Marshal.GetLastWin32Error() == 0 ? 1 : 0);
                    }
                }
            }

            // Clear up the data:
            Marshal.FreeCoTaskMem(ptrData);
        }
        stream.Close();

        return(recipients);
    }
예제 #37
0
파일: Windows.cs 프로젝트: labeuze/source
 public static IntPtr[] GetWindowsList()
 {
     EnumWindows enumWindows = new EnumWindows();
     return enumWindows.GetWindowsList().ToArray();
 }
예제 #38
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

#if WIN32
            if (Environment.Is64BitOperatingSystem)
            {
                var resourceName  = "SmartSystemMenu.SmartSystemMenu64.exe";
                var fileName      = "SmartSystemMenu64.exe";
                var directoryName = Path.GetDirectoryName(AssemblyUtils.AssemblyLocation);
                var filePath      = Path.Combine(directoryName, fileName);
                try
                {
                    if (!File.Exists(filePath))
                    {
                        AssemblyUtils.ExtractFileFromAssembly(resourceName, filePath);
                    }
                    _64BitProcess = Process.Start(filePath);
                }
                catch
                {
                    string message = string.Format("Failed to load {0} process!", fileName);
                    MessageBox.Show(message, AssemblyUtils.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Close();
                    return;
                }
            }

            if (_settings.ShowSystemTrayIcon)
            {
                _systemTrayMenu = new SystemTrayMenu(_settings.Language);
                _systemTrayMenu.MenuItemAutoStartClick += MenuItemAutoStartClick;
                _systemTrayMenu.MenuItemSettingsClick  += MenuItemSettingsClick;
                _systemTrayMenu.MenuItemAboutClick     += MenuItemAboutClick;
                _systemTrayMenu.MenuItemExitClick      += MenuItemExitClick;
                _systemTrayMenu.Create();
                _systemTrayMenu.CheckMenuItemAutoStart(AutoStarter.IsAutoStartByRegisterEnabled(AssemblyUtils.AssemblyProductName, AssemblyUtils.AssemblyLocation));
            }

            var moduleName = Process.GetCurrentProcess().MainModule.ModuleName;

            _hotKeyHook         = new HotKeyHook();
            _hotKeyHook.Hooked += HotKeyHooked;
            if (_settings.MenuItems.Items.Flatten(x => x.Items).Any(x => x.Type == MenuItemType.Item && x.Key3 != VirtualKey.None && x.Show) || _settings.MenuItems.WindowSizeItems.Any(x => x.Key3 != VirtualKey.None))
            {
                _hotKeyHook.Start(moduleName, _settings.MenuItems);
            }

            _hotKeyMouseHook         = new HotKeys.MouseHook();
            _hotKeyMouseHook.Hooked += HotKeyMouseHooked;
            if (_settings.Closer.MouseButton != MouseButton.None)
            {
                _hotKeyMouseHook.Start(moduleName, _settings.Closer.Key1, _settings.Closer.Key2, _settings.Closer.MouseButton);
            }
#endif
            _windows = EnumWindows.EnumAllWindows(_settings, _windowSettings, new string[] { SHELL_WINDOW_NAME }).ToList();

            foreach (var window in _windows)
            {
                var processPath = window.Process?.GetMainModuleFileName() ?? string.Empty;
                var fileName    = Path.GetFileName(processPath);
                if (!string.IsNullOrEmpty(fileName) && _settings.ProcessExclusions.Contains(fileName.ToLower()))
                {
                    continue;
                }

                var isAdded = window.Menu.Create();
                if (isAdded)
                {
                    window.Menu.CheckMenuItem(window.ProcessPriority.GetMenuItemId(), true);
                    if (window.AlwaysOnTop)
                    {
                        window.Menu.CheckMenuItem(MenuItemId.SC_TOPMOST, true);
                    }

                    if (window.IsExToolWindow)
                    {
                        window.Menu.CheckMenuItem(MenuItemId.SC_HIDE_FOR_ALT_TAB, true);
                    }

                    var windowClassName = window.GetClassName();
                    var states          = _windowSettings.Find(windowClassName, processPath);
                    if (states.Any())
                    {
                        window.ApplyState(states[0], _settings.SaveSelectedItems, _settings.MenuItems.WindowSizeItems);
                        window.Menu.CheckMenuItem(MenuItemId.SC_SAVE_SELECTED_ITEMS, true);
                    }
                }
            }

            _callWndProcHook              = new CallWndProcHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE);
            _callWndProcHook.CallWndProc += WindowProc;
            _callWndProcHook.Start();

            _getMsgHook         = new GetMsgHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE);
            _getMsgHook.GetMsg += WindowGetMsg;
            _getMsgHook.Start();

            _shellHook = new ShellHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE);
            _shellHook.WindowCreated   += WindowCreated;
            _shellHook.WindowDestroyed += WindowDestroyed;
            _shellHook.Start();

            _cbtHook = new CBTHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE);
            _cbtHook.WindowCreated   += WindowCreated;
            _cbtHook.WindowDestroyed += WindowDestroyed;
            _cbtHook.MoveSize        += WindowMoveSize;
            _cbtHook.MinMax          += WindowMinMax;
            _cbtHook.Start();


            _mouseHook = new Hooks.MouseHook(Handle, MenuItemId.SC_DRAG_BY_MOUSE);
            var dragByMouseItemName = MenuItemId.GetName(MenuItemId.SC_DRAG_BY_MOUSE);
            if (_settings.MenuItems.Items.Flatten(x => x.Items).Any(x => x.Type == MenuItemType.Item && x.Name == dragByMouseItemName && x.Show))
            {
                _mouseHook.Start();
            }

            Hide();
        }
예제 #39
0
파일: Windows.cs 프로젝트: 24/source_04
        public static IntPtr[] GetThreadWindowsList(int threadId)
        {
            EnumWindows enumWindows = new EnumWindows();

            return(enumWindows.GetThreadWindowsList(threadId).ToArray());
        }