Пример #1
0
 internal Rect(User32.RECT rect)
 {
     Left = rect.Left;
     Top = rect.Top;
     Right = rect.Right;
     Bottom = rect.Bottom;
 }
Пример #2
0
 public ApplicationWindow(int processId, string processName, User32.NotificationAreaWindow notificationArea)
     : this(notificationArea.Text, notificationArea.MainWindowHandle, processId, processName)
 {
     this.Button = notificationArea.TBBUTTON;
     this.NotificationIconHwnd = notificationArea.ToolBarIconHandle;
     this.NotificationAreaWindow = notificationArea;
 }
 private static void HandleKey(User32.VirtualKey key, User32.ModifierKeys modkey, int id)
 {
     if (handlers.Value.ContainsKey(id))
     {
         handlers.Value[id].Action(key, modkey);
     }
 }
Пример #4
0
 private IntPtr SetKeyboardHandler(User32.InputHookHandler hook)
 {
     using (var module = Process.GetCurrentProcess().MainModule)
     {
         return User32.SetWindowsHookEx(KeyboardHookID, hook, Kernel32.GetModuleHandle(module.ModuleName), 0);
     }
 }
Пример #5
0
 private void OnF11Pressed(User32.VirtualKey key, User32.ModifierKeys modkey)
 {
     MessageBox.Show("F11 pulsado");
     stop = true;
     // Espera que acabe el bucle normalmente
     this.worker.Join();
 }
Пример #6
0
        public static Image WindowWithMarker(IntPtr handle, User32.POINT marker)
        {
            // get te hDC of the target window
            IntPtr hdcSrc = User32.GetWindowDC(handle);
            // get the size
            User32.RECT windowRect = new User32.RECT();
            User32.GetWindowRect(handle, ref windowRect);
            int width = windowRect.right - windowRect.left;
            int height = windowRect.bottom - windowRect.top;
            // create a device context we can copy to
            IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
            // create a bitmap we can copy it to,
            // using GetDeviceCaps to get the width/height
            IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
            // select the bitmap object
            IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
            // bitblt over
            GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY);
            // restore selection
            GDI32.SelectObject(hdcDest, hOld);
            // clean up
            GDI32.DeleteDC(hdcDest);
            User32.ReleaseDC(handle, hdcSrc);
            // get a .NET image object for it
            Image img = Image.FromHbitmap(hBitmap);
            // free up the Bitmap object
            GDI32.DeleteObject(hBitmap);

            // Add Marker
            // Create a custom brush using a semi-transparent color, and
            Color customColor = Color.FromArgb(75, Color.Red);
            SolidBrush shadowBrush = new SolidBrush(customColor);
            // Set image as a graphics context
            Graphics graphics = Graphics.FromImage(img);
            // Resolve mouse coords
            int size = 30;
            int x = marker.X - windowRect.left;
            int y = marker.Y - windowRect.top;
            // Create drawing rectangle
            Rectangle rect = new Rectangle(x - (size / 2), y - (size / 2), 30, 30);
            Rectangle crect = new Rectangle(x, y, 30, 30);
            // Draw circle
            graphics.FillEllipse(shadowBrush, rect);
            // Dispose of the brush.
            shadowBrush.Dispose();
            // Draw cursor
            System.Windows.Forms.Cursors.Default.Draw(graphics, crect);
            return img;
        }
Пример #7
0
        /// <summary>
        /// Set the values of each component to what it is configured to.
        /// </summary>
        private void SetValues()
        {
            User32 helper = new User32();
            helper.FindValidDisplayModes();

            List<User32.DEVMODE> screens = helper.AvailScrRes;
            List<object> screenList = new List<object>(screens.Count);
            for (int i = 0; i < screens.Count; i++)
            {
                if (screens[i].dmPelsWidth < 800 || screens[i].dmPelsHeight < 600)
                {
                    // Too small: skip.
                    continue;
                }

                object format = (screens[i].dmPelsWidth + "x" + screens[i].dmPelsHeight);
                if (screenList.Contains(format)) {
                    continue;
                }

                screenList.Add(format);
            }

            screenList.Sort(SortResolutions);

            // Video options:
            resolutionBox.Items.AddRange(screenList.ToArray());
            if (screenList.Contains(options.videoOptions.Resolution))
            {
                resolutionBox.SelectedItem = options.videoOptions.Resolution;
            }
            else
            {
                resolutionBox.SelectedItem = VTankOptions.getDefaultVideoOptions().Resolution;
            }

            checkBox1.Checked = !Boolean.Parse(options.videoOptions.Windowed);
            textureQualityBox.SelectedItem = options.videoOptions.TextureQuality;
            antialiasingBox.SelectedItem = options.videoOptions.AntiAliasing;
            shadingSupportCheckbox.Checked = Boolean.Parse(options.videoOptions.ShadingEnabled);

            // Audio options:
            soundBar.Value = int.Parse(options.audioOptions.ambientSound.Volume);
            soundMuteCheckbox.Checked = Boolean.Parse(
                options.audioOptions.ambientSound.Muted);
            soundBar.Enabled = !soundMuteCheckbox.Checked;

            bgMusicSlider.Value = int.Parse(options.audioOptions.backgroundSound.Volume);
            bgMuteCheckbox.Checked = Boolean.Parse(
                options.audioOptions.backgroundSound.Muted);
            bgMusicSlider.Enabled = !bgMuteCheckbox.Checked;

            // Gameplay options:
            showPlayerNamesCheckbox.Checked = Boolean.Parse(
                options.gamePlayOptions.ShowNames);
            profanityFilterCheckbox.Checked = Boolean.Parse(
                options.gamePlayOptions.ProfanityFilter);
            interfacePluginBox.SelectedIndex = 0;

            // Control options:
            KeysConverter kc = new KeysConverter();
            forwardValue.Text = kc.ConvertToString(options.keyBindings.Forward);
            backwardValue.Text = kc.ConvertToString(options.keyBindings.Backward);
            rotateLeftValue.Text = kc.ConvertToString(options.keyBindings.RotateLeft);
            rotateRightValue.Text = kc.ConvertToString(options.keyBindings.RotateRight);
            //firePrimaryValue.Text = kc.ConvertToString(options.keyBindings.FirePrimary);
            //fireSecondaryValue.Text = kc.ConvertToString(options.keyBindings.FireSecondary);
            menuValue.Text = kc.ConvertToString(options.keyBindings.Menu);
            largeMapValue.Text = kc.ConvertToString(options.keyBindings.Minimap);
            scoreboardValue.Text = kc.ConvertToString(options.keyBindings.Score);
            cameraValue.Text = kc.ConvertToString(options.keyBindings.Camera);

            ImageList images = new ImageList();
            Dictionary<String, Icon> cursors = GetAvailableCursors();
            foreach (string key in cursors.Keys)
            {
                Icon icon = cursors[key];
                images.Images.Add(key, icon);
            }

            pointerBox.ImageList = images;

            int index = 0;
            foreach (string key in cursors.Keys)
            {
                pointerBox.Items.Add(new ImageComboBoxItem(key, index));
                if (options.keyBindings.Pointer == key)
                {
                    pointerBox.SelectedIndex = index;
                }
                ++index;
            }

            pointerBox.SelectedIndexChanged += new EventHandler(pointerBox_SelectedIndexChanged);
        }
        private void CreateWindow(string className)
        {
            if (className == null)
            {
                throw new Exception("class_name is null");
            }
            if (className == String.Empty)
            {
                throw new Exception("class_name is empty");
            }

            _wndProcDelegate = CustomWndProc;

            gcHandle = GCHandle.Alloc(_wndProcDelegate);

            WNDCLASS windClass = new WNDCLASS
            {
                lpszClassName = className,
                lpfnWndProc   = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate)
            };

            ushort classAtom = User32.RegisterClassW(ref windClass);

            int lastError = Marshal.GetLastWin32Error();

            if (classAtom == 0 && lastError != ERROR_CLASS_ALREADY_EXISTS)
            {
                throw new Exception("Could not register window class");
            }

            const UInt32 extendedStyle = (UInt32)(
                WindowExStyles.WS_EX_LEFT |
                WindowExStyles.WS_EX_LTRREADING |
                WindowExStyles.WS_EX_RIGHTSCROLLBAR |
                WindowExStyles.WS_EX_TOOLWINDOW);

            const UInt32 style = (UInt32)(
                WindowStyles.WS_CLIPSIBLINGS |
                WindowStyles.WS_CLIPCHILDREN |
                WindowStyles.WS_POPUP);

            var owner = User32.GetWindow(_parentHandle, 4);

            // Create window
            _handle = User32.CreateWindowExW(
                extendedStyle,
                className,
                className,
                style,
                0,
                0,
                0,
                0,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero
                );

            if (_handle == IntPtr.Zero)
            {
                return;
            }

            uint styles = User32.GetWindowLong(_handle, GetWindowLongFlags.GWL_EXSTYLE);

            styles = styles | (int)WindowExStyles.WS_EX_LAYERED | (int)WindowExStyles.WS_EX_NOACTIVATE | (int)WindowExStyles.WS_EX_TRANSPARENT;
            User32.SetWindowLong(_handle, GetWindowLongFlags.GWL_EXSTYLE, styles);
        }
Пример #9
0
 private void OnF10Pressed(User32.VirtualKey key, User32.ModifierKeys modkey)
 {
     stop = false;
     this.worker = new Thread (TestCodes);
     this.worker.Start();
 }
Пример #10
0
 /// <summary>
 /// Overridden OnGotFocus that removes the selection rectangle</summary>
 /// <param name="e">Event arguments</param>
 /// <remarks>See http://stackoverflow.com/questions/1484270/hiding-dashed-outline-around-trackbar-control-when-selected. </remarks>
 protected override void OnGotFocus(EventArgs e)
 {
     base.OnGotFocus(e);
     User32.SendMessage(Handle, User32.WM_UPDATEUISTATE, MakeParam(1, 0x1), 0);
 }
        internal void Show(bool show)
        {
            const int swShowNoActivate = 4;

            User32.ShowWindow(_handle, show ? swShowNoActivate : 0);
        }
		bool IsResponding( uint timeout, User32.SendMessageTimeoutFlags callFlags )
		{
			User32.SendMessageTimeoutFlags flags = callFlags |
				User32.SendMessageTimeoutFlags.AbortIfHung |
				User32.SendMessageTimeoutFlags.Block;

			IntPtr result;
			var responding = (int)User32.SendMessageTimeout(
				Handle, 0, IntPtr.Zero, IntPtr.Zero, callFlags,
				timeout, out result );

			return responding != 0;
		}
Пример #13
0
        private static void GetTrayWndRect(ref User32.RECT lpRect)
        {
            int defaultWidth = 150;
            int defaultHeight = 30;

            int hwndShellTray = User32.FindWindow("Shell_TrayWnd", null);

            if (hwndShellTray != 0)
            {
                User32.GetWindowRect(hwndShellTray, ref lpRect);

                User32.EnumChildProc callback = new User32.EnumChildProc(FindTrayWindow);
                User32.EnumChildWindows(hwndShellTray, callback, ref lpRect);
            }
            else
            {
                // OK. Haven't found a thing. Provide a default rect based on the current work
                // area

                System.Drawing.Rectangle workArea = SystemInformation.WorkingArea;
                lpRect.right = workArea.Right;
                lpRect.bottom = workArea.Bottom;
                lpRect.left = workArea.Right - defaultWidth;
                lpRect.top  = workArea.Bottom - defaultHeight;
            }
        }
Пример #14
0
 private void OnF11Pressed(User32.VirtualKey key, User32.ModifierKeys modkey)
 {
 }
Пример #15
0
 private static uint GetUSERObjectsCount()
 {
     return(User32.GetGuiResources(Process.GetCurrentProcess().Handle, 1));
 }
Пример #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="nCode"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        protected IntPtr HookProcHandler(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            {
                MessageType     flag    = (MessageType)wParam;
                KBDLLHOOKSTRUCT keyData = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(KBDLLHOOKSTRUCT));

                Console.WriteLine("Flag:{0} KeyData:{1}", flag, keyData);


                //按下控制键
                if ((KeyDown != null || KeyPress != null) && (flag == MessageType.WM_KEYDOWN || flag == MessageType.WM_SYSKEYDOWN))
                {
                    if (IsCtrlAltShiftKeys(keyData.vkCode) && KeysList.IndexOf(keyData) == -1)
                    {
                        KeysList.Add(keyData);
                    }
                }
                //松开控制键
                if ((KeyDown != null || KeyPress != null) && (flag == MessageType.WM_KEYUP || flag == MessageType.WM_SYSKEYUP))
                {
                    if (IsCtrlAltShiftKeys(keyData.vkCode))
                    {
                        for (int i = KeysList.Count - 1; i >= 0; i--)
                        {
                            if (KeysList[i].vkCode == keyData.vkCode)
                            {
                                KeysList.RemoveAt(i);
                            }
                        }
                    }
                }

                if (KeyDown != null && (flag == MessageType.WM_KEYDOWN || flag == MessageType.WM_SYSKEYDOWN))
                {
                    KeyEventArgs Args = new KeyEventArgs(null, null, (int)keyData.time, KeyInterop.KeyFromVirtualKey((int)keyData.vkCode));
                    KeyDown(this, Args);
                }

                if (KeyUp != null && (flag == MessageType.WM_KEYUP || flag == MessageType.WM_SYSKEYUP))
                {
                    KeyEventArgs Args = new KeyEventArgs(null, null, (int)keyData.time, KeyInterop.KeyFromVirtualKey((int)keyData.vkCode));
                    KeyUp(this, Args);
                }

                if (KeyPress != null && flag == MessageType.WM_KEYDOWN)
                {
                    byte[] keyState = new byte[256];
                    User32.GetKeyboardState(keyState);
                    byte[] inBuffer = new byte[2];

                    if (User32.ToAscii(keyData.vkCode, (uint)keyData.scanCode, keyState, inBuffer, (uint)keyData.flags) == 1)
                    {
                        Console.WriteLine("KeyChar:{0}", (char)inBuffer[0]);
                        Key k = KeyInterop.KeyFromVirtualKey((int)keyData.vkCode);
                    }
                }
            }

            return(User32.CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam));
        }
Пример #17
0
 public System.Drawing.Image CaptureScreen()
 {
     return(CaptureWindow(User32.GetDesktopWindow()));
 }
Пример #18
0
 /// <summary>
 /// call the next hook in the chain
 /// </summary>
 protected IntPtr CallNextHook(int nCode, UIntPtr wParam, IntPtr lParam)
 {
     return(User32.CallNextHookEx(m_hHook, nCode, wParam, lParam));
 }
 public HotkeyHandler(User32.VirtualKey key, User32.ModifierKeys modkey, HotkeyAction action)
 {
     this.Key = key;
     this.ModKey = modkey;
     this.Action = action;
 }
 public HotkeyHandler(User32.VirtualKey key, HotkeyAction action)
     : this(key, User32.ModifierKeys.None, action)
 {
 }
Пример #21
0
        public HResult ExtractAndDrawThumbnail(IntPtr hdc, uint iconSize, out WTS_CACHEFLAGS flags, User32.RECT iconBounds, out bool retrieved, bool isHidden, bool isRefresh = false)
        {
            HResult res = HResult.S_OK;
            ISharedBitmap bmp = null;
            flags = WTS_CACHEFLAGS.WTS_DEFAULT;
            WTS_THUMBNAILID thumbId = new WTS_THUMBNAILID();
            try
            {
                retrieved = false;
                res = ThumbnailCache.GetThumbnail(this._Item.ComInterface, iconSize, isRefresh ? (WTS_FLAGS.WTS_FORCEEXTRACTION | WTS_FLAGS.WTS_SCALETOREQUESTEDSIZE) : (WTS_FLAGS.WTS_INCACHEONLY | WTS_FLAGS.WTS_SCALETOREQUESTEDSIZE), out bmp, flags, thumbId);
                IntPtr hBitmap = IntPtr.Zero;
                if (bmp != null)
                {
                    bmp.GetSharedBitmap(out hBitmap);
                    retrieved = true;

                    int width;
                    int height;
                    Gdi32.ConvertPixelByPixel(hBitmap, out width, out height);
                    Gdi32.NativeDraw(hdc, hBitmap, iconBounds.Left + (iconBounds.Right - iconBounds.Left - width) / 2, iconBounds.Top + (iconBounds.Bottom - iconBounds.Top - height) / 2, width, height, isHidden);
                    Gdi32.DeleteObject(hBitmap);
                }
            }
            finally
            {
                if (bmp != null) Marshal.ReleaseComObject(bmp);
            }
            return res;
        }
Пример #22
0
 public static extern bool DeleteDC(User32.SafeDCHandle hDC);
Пример #23
0
    private void ProcessCustomDrawPostPaint(ref Message m, User32.NMLVCUSTOMDRAW nmlvcd, Int32 index, IntPtr hdc, IListItemEx sho, Color? textColor) {
      if (nmlvcd.clrTextBk != 0 && nmlvcd.dwItemType == 0 && this._CurrentDrawIndex == -1) {
        //var perceivedType = (PerceivedType)sho.GetPropertyValue(SystemProperties.PerceivedType, typeof(PerceivedType)).Value;
        this._CurrentDrawIndex = index;
        var itemBounds = nmlvcd.nmcd.rc;
        var lvi = new LVITEMINDEX();
        lvi.iItem = index;
        lvi.iGroup = this.GetGroupIndex(index);
        var iconBounds = new User32.RECT() { Left = 1 };
        User32.SendMessage(this.LVHandle, MSG.LVM_GETITEMINDEXRECT, ref lvi, ref iconBounds);
        var lvItem = new LVITEM() {
          iItem = index,
          iGroupId = lvi.iGroup,
          iGroup = lvi.iGroup,
          mask = LVIF.LVIF_STATE,
          stateMask = LVIS.LVIS_SELECTED
        };
        var lvItemImageMask = new LVITEM() {
          iItem = index,
          iGroupId = lvi.iGroup,
          iGroup = lvi.iGroup,
          mask = LVIF.LVIF_STATE,
          stateMask = LVIS.LVIS_STATEIMAGEMASK
        };

        if (sho != null) {
          var cutFlag = (User32.SendMessage(this.LVHandle, MSG.LVM_GETITEMSTATE, index, LVIS.LVIS_CUT) & LVIS.LVIS_CUT) ==
                                                                  LVIS.LVIS_CUT;
          if (this.IconSize == 16) {
            this.SmallImageList.DrawIcon(hdc, index, sho, iconBounds,
                    sho.IsHidden || cutFlag || this._CuttedIndexes.Contains(index), (nmlvcd.nmcd.uItemState & CDIS.HOT) == CDIS.HOT);
          } else {
            this.LargeImageList.DrawIcon(hdc, index, sho, iconBounds,
                    sho.IsHidden || cutFlag || this._CuttedIndexes.Contains(index), (nmlvcd.nmcd.uItemState & CDIS.HOT) == CDIS.HOT);
          }

          if (!sho.IsInitialised) sho.IsInitialised = true;
        }
        m.Result = (IntPtr)CustomDraw.CDRF_SKIPDEFAULT;
      } else {
        m.Result = IntPtr.Zero;
      }

      this._CurrentDrawIndex = -1;
    }
Пример #24
0
 /// <summary>
 ///     Calculates the x-coordinate with the system metric.
 /// </summary>
 private static int CalculateAbsoluteCoordinateX(int x)
 {
     return(x * 65536 / User32.GetSystemMetrics(SystemMetrics.CxScreen));
 }
Пример #25
0
 private static void CropRect(ref User32.RECT windowRect, int x, int y, int w, int h)
 {
     windowRect.left = (x > 0) ? Math.Min(windowRect.right, windowRect.left + x) : windowRect.left;
     windowRect.right = (w > 0) ? Math.Min(windowRect.right, windowRect.left + w) : windowRect.right;
     windowRect.top = (y > 0) ? Math.Min(windowRect.bottom, windowRect.top + y) : windowRect.top;
     windowRect.bottom = (h > 0) ? Math.Min(windowRect.bottom, windowRect.top + h) : windowRect.bottom;
 }
Пример #26
0
 public static Bitmap CaptureActiveWindow()
 {
     return(CaptureWindowDifferentFunction(User32.GetForegroundWindow()));
 }
Пример #27
0
        private void UpdateCardTooltip()
        {
            var pos = User32.GetMousePos();
            var relativePlayerDeckPos   = ViewBoxPlayer.PointFromScreen(new Point(pos.X, pos.Y));
            var relativeOpponentDeckPos = ViewBoxOpponent.PointFromScreen(new Point(pos.X, pos.Y));
            var relativeSecretsPos      = StackPanelSecrets.PointFromScreen(new Point(pos.X, pos.Y));
            var relativeCardMark        = _cardMarks.Select(x => new { Label = x, Pos = x.PointFromScreen(new Point(pos.X, pos.Y)) });
            var visibility = (Config.Instance.OverlayCardToolTips && !Config.Instance.OverlaySecretToolTipsOnly)
                                                                 ? Visible : Hidden;

            var cardMark =
                relativeCardMark.FirstOrDefault(
                    x =>
                    x.Label.IsVisible && PointInsideControl(x.Pos, x.Label.ActualWidth, x.Label.ActualHeight, new Thickness(3, 1, 7, 1)));

            if (!Config.Instance.HideOpponentCardMarks && cardMark != null)
            {
                var index = _cardMarks.IndexOf(cardMark.Label);
                var card  = _game.Opponent.Hand.FirstOrDefault(x => x.GetTag(GameTag.ZONE_POSITION) == index + 1 && x.HasCardId && !x.Info.Hidden)?.Card;
                if (card != null)
                {
                    ToolTipCard.SetValue(DataContextProperty, card);
                    var topOffset  = Canvas.GetTop(_cardMarks[index]) + _cardMarks[index].ActualHeight;
                    var leftOffset = Canvas.GetLeft(_cardMarks[index]) + _cardMarks[index].ActualWidth * index;
                    Canvas.SetTop(ToolTipCard, topOffset);
                    Canvas.SetLeft(ToolTipCard, leftOffset);
                    ToolTipCard.Visibility = Config.Instance.OverlayCardMarkToolTips ? Visible : Hidden;
                }
            }
            //player card tooltips
            else if (ListViewPlayer.Visibility == Visible && StackPanelPlayer.Visibility == Visible &&
                     PointInsideControl(relativePlayerDeckPos, ListViewPlayer.ActualWidth, ListViewPlayer.ActualHeight))
            {
                //card size = card list height / amount of cards
                var cardSize  = ViewBoxPlayer.ActualHeight / ListViewPlayer.Items.Count;
                var cardIndex = (int)(relativePlayerDeckPos.Y / cardSize);
                if (cardIndex < 0 || cardIndex >= ListViewPlayer.Items.Count)
                {
                    return;
                }

                ToolTipCard.SetValue(DataContextProperty, ListViewPlayer.Items.Cast <AnimatedCard>().ElementAt(cardIndex).Card);

                var centeredListOffset = Config.Instance.OverlayCenterPlayerStackPanel ? (BorderStackPanelPlayer.ActualHeight - StackPanelPlayer.ActualHeight) / 2 : 0;
                //offset is affected by scaling
                var topOffset = Canvas.GetTop(BorderStackPanelPlayer) + centeredListOffset
                                + GetListViewOffset(StackPanelPlayer) + cardIndex * cardSize * Config.Instance.OverlayPlayerScaling / 100;

                //prevent tooltip from going outside of the overlay
                if (topOffset + ToolTipCard.ActualHeight > Height)
                {
                    topOffset = Height - ToolTipCard.ActualHeight;
                }

                SetTooltipPosition(topOffset, BorderStackPanelPlayer);

                ToolTipCard.Visibility = visibility;
            }
            //opponent card tooltips
            else if (ListViewOpponent.Visibility == Visible && StackPanelOpponent.Visibility == Visible &&
                     PointInsideControl(relativeOpponentDeckPos, ListViewOpponent.ActualWidth, ListViewOpponent.ActualHeight))
            {
                //card size = card list height / amount of cards
                var cardSize  = ViewBoxOpponent.ActualHeight / ListViewOpponent.Items.Count;
                var cardIndex = (int)(relativeOpponentDeckPos.Y / cardSize);
                if (cardIndex < 0 || cardIndex >= ListViewOpponent.Items.Count)
                {
                    return;
                }

                ToolTipCard.SetValue(DataContextProperty, ListViewOpponent.Items.Cast <AnimatedCard>().ElementAt(cardIndex).Card);

                var centeredListOffset = Config.Instance.OverlayCenterOpponentStackPanel ? (BorderStackPanelOpponent.ActualHeight - StackPanelOpponent.ActualHeight) / 2 : 0;
                //offset is affected by scaling
                var topOffset = Canvas.GetTop(BorderStackPanelOpponent) + centeredListOffset
                                + GetListViewOffset(StackPanelOpponent) + cardIndex * cardSize * Config.Instance.OverlayOpponentScaling / 100;

                //prevent tooltip from going outside of the overlay
                if (topOffset + ToolTipCard.ActualHeight > Height)
                {
                    topOffset = Height - ToolTipCard.ActualHeight;
                }

                SetTooltipPosition(topOffset, BorderStackPanelOpponent);

                ToolTipCard.Visibility = visibility;
            }
            else if (StackPanelSecrets.Visibility == Visible &&
                     PointInsideControl(relativeSecretsPos, StackPanelSecrets.ActualWidth, StackPanelSecrets.ActualHeight))
            {
                //card size = card list height / amount of cards
                var cardSize  = StackPanelSecrets.ActualHeight / StackPanelSecrets.Children.Count;
                var cardIndex = (int)(relativeSecretsPos.Y / cardSize);
                if (cardIndex < 0 || cardIndex >= StackPanelSecrets.Children.Count)
                {
                    return;
                }

                ToolTipCard.SetValue(DataContextProperty, StackPanelSecrets.Children[cardIndex].GetValue(DataContextProperty));

                //offset is affected by scaling
                var topOffset = Canvas.GetTop(StackPanelSecrets) + cardIndex * cardSize * Config.Instance.OverlayOpponentScaling / 100;

                //prevent tooltip from going outside of the overlay
                if (topOffset + ToolTipCard.ActualHeight > Height)
                {
                    topOffset = Height - ToolTipCard.ActualHeight;
                }

                SetTooltipPosition(topOffset, StackPanelSecrets);

                ToolTipCard.Visibility = Config.Instance.OverlaySecretToolTipsOnly ? Visible : visibility;
            }
            else
            {
                ToolTipCard.Visibility = Hidden;
                HideAdditionalToolTips();
            }

            if (ToolTipCard.Visibility == Visible)
            {
                var card = ToolTipCard.GetValue(DataContextProperty) as Card;
                if (card != null)
                {
                    if (_lastToolTipCardId != card.Id)
                    {
                        _lastToolTipCardId = card.Id;
                        ShowAdditionalToolTips();
                    }
                }
                else
                {
                    HideAdditionalToolTips();
                }
            }
            else
            {
                HideAdditionalToolTips();
                _lastToolTipCardId = string.Empty;
            }


            if (!Config.Instance.ForceMouseHook)
            {
                if (Config.Instance.ExtraFeatures)
                {
                    var relativePos = PointFromScreen(new Point(pos.X, pos.Y));
                    if ((StackPanelSecrets.IsVisible &&
                         (PointInsideControl(StackPanelSecrets.PointFromScreen(new Point(pos.X, pos.Y)), StackPanelSecrets.ActualWidth,
                                             StackPanelSecrets.ActualHeight, new Thickness(20))) || relativePos.X < 170 && relativePos.Y > Height - 120))
                    {
                        if (_mouseInput == null)
                        {
                            HookMouse();
                        }
                    }
                    else if (_mouseInput != null && !((_isFriendsListOpen.HasValue && _isFriendsListOpen.Value) || Reflection.IsFriendsListVisible()))
                    {
                        UnHookMouse();
                    }
                }
                else if (_mouseInput != null)
                {
                    UnHookMouse();
                }
            }

            if (!Config.Instance.AlwaysShowGoldProgress)
            {
                if (_game.IsInMenu &&
                    PointInsideControl(RectGoldDisplay.PointFromScreen(new Point(pos.X, pos.Y)), RectGoldDisplay.ActualWidth,
                                       RectGoldDisplay.ActualHeight))
                {
                    UpdateGoldProgress();
                    GoldProgressGrid.Visibility = Visible;
                }
                else
                {
                    GoldProgressGrid.Visibility = Hidden;
                }
            }
        }
Пример #28
0
 /// <summary>
 ///     Calculates the y-coordinate with the system metric.
 /// </summary>
 private static int CalculateAbsoluteCoordinateY(int y)
 {
     return(y * 65536 / User32.GetSystemMetrics(SystemMetrics.CyScreen));
 }
Пример #29
0
 public static extern IntPtr CreateCompatibleBitmap(User32.SafeDCHandle hDC, int nWidth, int nHeight);
Пример #30
0
 /// <summary>
 /// Blocks user input
 /// </summary>
 /// <param name="blocked">true will block, false will unblock</param>
 /// <returns>true if the operation succeeded, otherwise false</returns>
 public static bool BlockInput(bool blocked = true)
 {
     return(User32.BlockInput(blocked));
 }
Пример #31
0
 public static Image CaptureDesktop()
 {
     return(CaptureWindowDifferentFunction(User32.GetDesktopWindow()));
 }
Пример #32
0
 /// <summary>
 /// Toggle volume mute
 /// </summary>
 public static void VolumeMute()
 {
     User32.keybd_event((byte)Forms.Keys.VolumeMute, 0, 0, 0);
 }
Пример #33
0
 /// <summary>
 /// Creates an Image object containing a screen shot of the entire desktop
 /// </summary>
 /// <returns></returns>
 public Image CaptureScreen()
 {
     return(CaptureWindow(User32.GetDesktopWindow()));
 }
Пример #34
0
        private void DoOperation(IntPtr win)
        {
            while (true)
            {
                //topLevelWin是本进程(?)内的顶层窗口
                //rootWindow可能会跨进程
                var topLevelWin = Native.GetTopLevelWindow(win);
                var rootWin     = Native.GetAncestor(topLevelWin, Native.GetAncestorFlags.GetRoot);

                if (rootWin == IntPtr.Zero)
                {
                    return;
                }

                Debug.WriteLine(string.Format("win     : {0:X}", win.ToInt64()));
                Debug.WriteLine(string.Format("root    : {0:X}", rootWin.ToInt64()));
                Debug.WriteLine(string.Format("topLevel: {0:X}", topLevelWin.ToInt64()));

                var rootWinStyle     = User32.GetWindowLong(rootWin, User32.GWL.GWL_STYLE);
                var topLevelWinstyle = User32.GetWindowLong(topLevelWin, User32.GWL.GWL_STYLE);

                switch (ChangeWindowStateTo)
                {
                case WindowOperation.MAXIMIZE_RESTORE:
                    IntPtr winToControl;
                    if ((long)User32.WS.WS_MAXIMIZEBOX == (topLevelWinstyle & (long)User32.WS.WS_MAXIMIZEBOX))
                    {
                        winToControl = topLevelWin;
                    }
                    else if (topLevelWin != rootWin && (long)User32.WS.WS_MAXIMIZEBOX == (rootWinStyle & (long)User32.WS.WS_MAXIMIZEBOX))
                    {
                        winToControl = rootWin;
                    }
                    else     //如果窗口都不响应, 考虑回滚为处理活动窗口
                    {
                        var fgWin = Native.GetForegroundWindow();
                        if (fgWin == win)
                        {
                            return;
                        }

                        win = fgWin;
                        continue;
                    }

                    var wp = new User32.WINDOWPLACEMENT();
                    wp.length = Marshal.SizeOf(typeof(User32.WINDOWPLACEMENT));

                    if (!User32.GetWindowPlacement(rootWin, ref wp))
                    {
                        return;
                    }

                    if (wp.showCmd == (int)ShowWindowCommands.MAXIMIZED)
                    {
                        User32.ShowWindowAsync(winToControl, (int)ShowWindowCommands.NORMAL);
                    }
                    else
                    {
                        User32.ShowWindowAsync(winToControl, (int)ShowWindowCommands.MAXIMIZED);
                    }
                    goto end;

                case WindowOperation.MINIMIZE:
                    if ((long)User32.WS.WS_MINIMIZEBOX == (rootWinStyle & (long)User32.WS.WS_MINIMIZEBOX))
                    {
                        User32.PostMessage(rootWin, User32.WM.WM_SYSCOMMAND, (int)User32.SysCommands.SC_MINIMIZE, 0);
                    }
                    else if (topLevelWin != rootWin && (long)User32.WS.WS_MINIMIZEBOX == (topLevelWinstyle & (long)User32.WS.WS_MINIMIZEBOX))
                    {
                        User32.PostMessage(topLevelWin, User32.WM.WM_SYSCOMMAND, (int)User32.SysCommands.SC_MINIMIZE, 0);
                    }
                    goto end;

                case WindowOperation.CLOSE:
                    User32.PostMessage(rootWin, User32.WM.WM_SYSCOMMAND, (int)User32.SysCommands.SC_CLOSE, 0);
                    goto end;
                }
                break;
            }

            end : GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        }
 internal void Close()
 {
     User32.CloseWindow(_handle);
     User32.SetParent(_handle, IntPtr.Zero);
     User32.DestroyWindow(_handle);
 }
Пример #36
0
 internal static HWND IWin2Ptr(System.Windows.Forms.IWin32Window wnd, bool desktopIfNull = true) => wnd?.Handle ?? User32.FindWindow("Progman", null);
        private Bitmap GetBitmap(int width, int height)
        {
            Bitmap bmp;

            switch (_side)
            {
            case ShadowFormDockPositon.Top:
            case ShadowFormDockPositon.Bottom:
                bmp = new Bitmap(width, Size, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                break;

            case ShadowFormDockPositon.Left:
            case ShadowFormDockPositon.Right:
                bmp = new Bitmap(Size, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            Graphics     g        = Graphics.FromImage(bmp);
            List <Color> colorMap = _parentWindowIsFocused ? _activeColors : _inactiveColors;

            RECT windowRect = new RECT();

            User32.GetWindowRect(_parentHandle, ref windowRect);



            if (_side == ShadowFormDockPositon.Top || _side == ShadowFormDockPositon.Bottom)
            {
                for (int i = 0; i < _alphas.Count; i++)
                {
                    Color     color  = Color.FromArgb((int)(_alphas[i] * (colorMap[i].A / 255f)), colorMap[i].R, colorMap[i].G, colorMap[i].B);
                    Pen       pen    = new Pen(color);
                    int       y      = (_side == ShadowFormDockPositon.Top) ? Size - 1 - i : i;
                    const int xLeft  = Size * 2 - 2;
                    int       xRight = width - Size * 2 + 2;
                    g.DrawLine(pen, new Point(xLeft, y), new Point(xRight, y));
                    double a = _alphas[i] / (Size + i);

                    for (int j = 0; j < Size; j++)
                    {
                        double al = Math.Max(0, _alphas[i] - a * j);
                        color = Color.FromArgb((int)(al * (colorMap[i].A / 255f)), colorMap[i].R, colorMap[i].G, colorMap[i].B);
                        System.Drawing.Brush b = new SolidBrush(color);
                        g.FillRectangle(b, xLeft - 1 - j, y, 1, 1);
                        g.FillRectangle(b, xRight + 1 + j, y, 1, 1);
                    }
                    for (int j = Size; j < Size + i; j++)
                    {
                        double al = Math.Max(0, _alphas[i] - a * j) / 2;
                        color = Color.FromArgb((int)(al * (colorMap[i].A / 255f)), colorMap[i].R, colorMap[i].G, colorMap[i].B);
                        System.Drawing.Brush b = new SolidBrush(color);
                        g.FillRectangle(b, xLeft - 1 - j, y, 1, 1);
                        g.FillRectangle(b, xRight + 1 + j, y, 1, 1);
                    }
                }
            }
            else
            {
                for (int i = 0; i < _alphas.Count; i++)
                {
                    Color     color   = Color.FromArgb((int)(_alphas[i] * (colorMap[i].A / 255f)), colorMap[i].R, colorMap[i].G, colorMap[i].B);
                    Pen       pen     = new Pen(color);
                    int       x       = (_side == ShadowFormDockPositon.Right) ? i : Size - i - 1;
                    const int yTop    = Size * 2 - 1;
                    int       yBottom = height - Size * 2 + 1;
                    g.DrawLine(pen, new Point(x, yTop), new Point(x, yBottom));

                    double a = _alphas[i] / (Size + i);
                    for (int j = 0; j < Size + 1; j++)
                    {
                        double al = Math.Max(0, _alphas[i] - a * j);
                        color = Color.FromArgb((int)(al * (colorMap[i].A / 255f)), colorMap[i].R, colorMap[i].G, colorMap[i].B);
                        System.Drawing.Brush b = new SolidBrush(color);
                        g.FillRectangle(b, x, yTop - 1 - j, 1, 1);
                        g.FillRectangle(b, x, yBottom + 1 + j, 1, 1);
                    }
                    for (int j = Size; j < Size + i + 1; j++)
                    {
                        double al = Math.Max(0, _alphas[i] - a * j) / 2;
                        color = Color.FromArgb((int)(al * (colorMap[i].A / 255f)), colorMap[i].R, colorMap[i].G, colorMap[i].B);
                        System.Drawing.Brush b = new SolidBrush(color);
                        g.FillRectangle(b, x, yTop - 1 - j, 1, 1);
                        g.FillRectangle(b, x, yBottom + 1 + j, 1, 1);
                    }
                }
            }
            g.Flush();


            return(bmp);
        }
Пример #38
0
        private void Window_SourceInitialized_1(object sender, EventArgs e)
        {
            var hwnd = new WindowInteropHelper(this).Handle;

            User32.SetWindowExStyle(hwnd, User32.WsExTransparent | User32.WsExToolWindow);
        }
Пример #39
0
        private void ClickTimerCallBack(Object source, ElapsedEventArgs e)
        {
            if (clickCount == 0)
            {
                // fix context menu position
                contextMenuStripSysTray.Show(Cursor.Position);
                return;
            }

            pauseUpgradeCounter = true;

            int keyPressed = -1;

            //check 0-9 key pressed
            for (int i = 0x30; i < 0x3a; ++i)
            {
                if (User32.GetAsyncKeyState(i) != 0)
                {
                    keyPressed = i;
                    break;
                }
            }

            //check a-z pressed
            if (keyPressed < 0)
            {
                for (int i = 0x41; i < 0x5b; ++i)
                {
                    if (User32.GetAsyncKeyState(i) != 0)
                    {
                        keyPressed = i;
                        break;
                    }
                }
            }

            int totalSpecialKeyPressed = shiftKeyPressed + controlKeyPressed + altKeyPressed;

            if (clickCount > 3)
            {
            }
            else if (totalSpecialKeyPressed > clickCount)
            {
                //no more than one key can be pressed
            }
            else if (shiftKeyPressed == clickCount && shiftKeyPressed != 0)
            {
                // take counted snapshot
                Program.CaptureSnapshot(clickCount);
            }
            else if (controlKeyPressed == clickCount && controlKeyPressed != 0)
            {
                //restore counted snapshot
                Program.RestoreSnapshot(clickCount);
            }
            else if (altKeyPressed == clickCount && altKeyPressed != 0)
            {
                //restore previous workspace (not necessarily a snapshot)
                Program.RestoreSnapshot(36); //MaxSnapShot - 1
            }
            else if (totalSpecialKeyPressed == 0)
            {
                if (keyPressed < 0)
                {
                    if (clickCount == 1 && firstClick && !doubleClick)
                    {
                        //restore unnamed(default) snapshot
                        Program.RestoreSnapshot(0);
                    }
                    else if (clickCount == 2 && firstClick && doubleClick)
                    {
                        Program.CaptureSnapshot(0);
                    }
                }
                else
                {
                    int snapshot;
                    if (keyPressed < 0x3a)
                    {
                        snapshot = keyPressed - 0x30;
                    }
                    else
                    {
                        snapshot = keyPressed - 0x41 + 10;
                    }

                    if (snapshot < 0 || snapshot > 35)
                    {
                        //invalid key pressed
                    }
                    else if (clickCount == 1 && firstClick && !doubleClick)
                    {
                        Program.RestoreSnapshot(snapshot);
                    }
                    else if (clickCount == 2 && firstClick && doubleClick)
                    {
                        Program.CaptureSnapshot(snapshot);
                    }
                }
            }

            clickCount        = 0;
            doubleClick       = false;
            firstClick        = false;
            shiftKeyPressed   = 0;
            controlKeyPressed = 0;
            altKeyPressed     = 0;
        }
			/// <summary>
			///   Initializes a <see cref="ShellExecuteInfo" /> correctly, in order to execute a given PIDL.
			/// </summary>
			/// <param name = "pidl">The PIDL to execute.</param>
			/// <param name = "show">Indicates how the application should be shown when it is opened.</param>
			public static ShellExecuteInfo ExecutePidl( IntPtr pidl, User32.WindowState show )
			{
				return new ShellExecuteInfo
				{
					StructSize = (uint)Marshal.SizeOf( typeof( ShellExecuteInfo ) ),
					Type = ShellExecuteInfoType.Pidl,
					Pidl = pidl,
					Show = show
				};
			}
Пример #41
0
 public static extern IntPtr GetWindowRect(IntPtr hWnd, ref User32.Rect rect);
Пример #42
0
 public static extern uint GetWindowLong(IntPtr hWnd, User32.GWL gwlIndex);
Пример #43
0
        private void RegisterMessageHandlers()
        {
            HubConnection.On("Chat", async(string message, string senderConnectionID) => {
                await ChatService.SendMessage(message, senderConnectionID, HubConnection);
            });
            HubConnection.On("ExecuteCommand", (async(string mode, string command, string commandID, string senderConnectionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Command attempted before server was verified.  Mode: {mode}.  Command: {command}.  Sender: {senderConnectionID}");
                    Uninstaller.UninstallAgent();
                    return;
                }

                await CommandExecutor.ExecuteCommand(mode, command, commandID, senderConnectionID, HubConnection);
            }));
            HubConnection.On("ExecuteCommandFromApi", (async(string mode, string requestID, string command, string commandID, string senderUserName) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Command attempted before server was verified.  Mode: {mode}.  Command: {command}.  Sender: {senderUserName}");
                    Uninstaller.UninstallAgent();
                    return;
                }

                await CommandExecutor.ExecuteCommandFromApi(mode, requestID, command, commandID, senderUserName, HubConnection);
            }));
            HubConnection.On("TransferFiles", async(string transferID, List <string> fileIDs, string requesterID) =>
            {
                Logger.Write($"File transfer started by {requesterID}.");
                var sharedFilePath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles")).FullName;

                foreach (var fileID in fileIDs)
                {
                    var url      = $"{ConnectionInfo.Host}/API/FileSharing/{fileID}";
                    var wr       = WebRequest.CreateHttp(url);
                    var response = await wr.GetResponseAsync();
                    var cd       = response.Headers["Content-Disposition"];
                    var filename = cd
                                   .Split(";")
                                   .FirstOrDefault(x => x.Trim()
                                                   .StartsWith("filename"))
                                   .Split("=")[1];

                    var legalChars = filename.ToCharArray().Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y));

                    filename = new string(legalChars.ToArray());

                    using (var rs = response.GetResponseStream())
                    {
                        using (var fs = new FileStream(Path.Combine(sharedFilePath, filename), FileMode.Create))
                        {
                            rs.CopyTo(fs);
                        }
                    }
                }
                await this.HubConnection.InvokeAsync("TransferCompleted", transferID, requesterID);
            });
            HubConnection.On("DeployScript", async(string mode, string fileID, string commandContextID, string requesterID) => {
                if (!IsServerVerified)
                {
                    Logger.Write($"Script deploy attempted before server was verified.  Mode: {mode}.  File ID: {fileID}.  Sender: {requesterID}");
                    Uninstaller.UninstallAgent();
                    return;
                }

                await ScriptRunner.RunScript(mode, fileID, commandContextID, requesterID, HubConnection);
            });
            HubConnection.On("UninstallClient", () =>
            {
                Uninstaller.UninstallAgent();
            });

            HubConnection.On("RemoteControl", async(string requesterID, string serviceID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Remote control attempted before server was verified.");
                    Uninstaller.UninstallAgent();
                    return;
                }
                await AppLauncher.LaunchRemoteControl(requesterID, serviceID, HubConnection);
            });
            HubConnection.On("RestartScreenCaster", async(List <string> viewerIDs, string serviceID, string requesterID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Remote control attempted before server was verified.");
                    Uninstaller.UninstallAgent();
                    return;
                }
                await AppLauncher.RestartScreenCaster(viewerIDs, serviceID, requesterID, HubConnection);
            });
            HubConnection.On("CtrlAltDel", () =>
            {
                User32.SendSAS(false);
            });

            HubConnection.On("ServerVerificationToken", (string verificationToken) =>
            {
                if (verificationToken == ConnectionInfo.ServerVerificationToken)
                {
                    IsServerVerified = true;
                    if (!Program.IsDebug)
                    {
                        _ = Task.Run(Updater.CheckForUpdates);
                    }
                }
                else
                {
                    Logger.Write($"Server sent an incorrect verification token.  Token Sent: {verificationToken}.");
                    Uninstaller.UninstallAgent();
                    return;
                }
            });
        }
Пример #44
0
 private void RedrawWindow(User32.RECT rect) { }// => User32.InvalidateRect(this.LVHandle, ref rect, false);
Пример #45
0
 public HResult ExtractAndDrawThumbnail(IntPtr hdc, uint iconSize, out WTS_CACHEFLAGS flags, User32.RECT iconBounds, out bool retrieved, bool isHidden, bool isRefresh = false) {
   return this._Item.Thumbnail.ExtractAndDrawThumbnail(hdc, iconSize, out flags, iconBounds, out retrieved, isHidden, isRefresh);
 }
Пример #46
0
        public Toggler(string[] args)
        {
            _args = args;

            // Always on top
            if (Settings.Instance.AlwaysOnTop)
            {
                TopMostWindow.SetTopMost(_process);
            }

            // Hide from taskbar
            User32.SetWindowLong(_process.MainWindowHandle, User32.GWL_EX_STYLE, (User32.GetWindowLong(_process.MainWindowHandle, User32.GWL_EX_STYLE) | User32.WS_EX_TOOLWINDOW) & ~User32.WS_EX_APPWINDOW);

            User32.Rect rect = default;
            User32.ShowWindow(_process.MainWindowHandle, NCmdShow.MAXIMIZE);

            var isOpen = true;

            // Register hotkeys
            Settings.Get(s =>
            {
                if (s.Hotkeys == null)
                {
                    return;                                    // Hotkeys not loaded yet
                }
                _registeredHotKeys.ForEach(hk => HotKeyManager.UnregisterHotKey(hk));
                _registeredHotKeys.Clear();

                s.Hotkeys.ForEach(hk =>
                {
                    Log.Information($"Registering hot key {hk.Modifiers} + {hk.Key}");
                    var reg = HotKeyManager.RegisterHotKey(hk.Key, hk.Modifiers);
                    _registeredHotKeys.Add(reg);
                });
            });

            // Hide on focus lost
            FocusTracker.OnFocusLost += (s, a) =>
            {
                if (Settings.Instance.HideOnFocusLost && isOpen)
                {
                    isOpen = false;
                    Toggle(false, 0);
                }
            };

            // Toggle on hotkey(s)
            HotKeyManager.HotKeyPressed += (s, a) =>
            {
                Toggle(!isOpen, Settings.Instance.ToggleDurationMs);
                isOpen = !isOpen;
            };

            // Start hidden?
            if (Settings.Instance.StartHidden)
            {
                Toggle(!isOpen, 0);
                isOpen = false;
            }
            else
            {
                Toggle(isOpen, 0);
                isOpen = true;
            }
        }
Пример #47
0
 public static extern int SetWindowLong(IntPtr hWnd, User32.GWL gwlIndex, uint dwNewLong);
Пример #48
0
        public Image CaptureCurrentWindow()
        {
            IntPtr ptr = User32.GetForegroundWindow();

            return(CaptureWindowFromScreen(ptr));
        }
Пример #49
0
 internal static extern bool GetCursorPos(ref User32.POINT pt);
Пример #50
0
        private void Scene_OnMouseMove(object sender, MouseEventArgs e)
        {
            if (!IsActive)
            {
                _moving = false;
                return;
            }

            _mousePos = e.GetPosition(Scene);

            if (Math.Abs(_mousePos.X - _startMousePos.X) > 2 || Math.Abs(_mousePos.Y - _startMousePos.Y) > 2)
            {
                _moved = true;
            }

            if (_moving && !_down)
            {
                var dx = _mousePos.X - _lastMousePos.X;
                var dy = _mousePos.Y - _lastMousePos.Y;

                var renderer = Model.Renderer;
                if (Keyboard.Modifiers == ModifierKeys.Alt)
                {
                    if (e.MiddleButton == MouseButtonState.Pressed || e.LeftButton == MouseButtonState.Pressed && User32.IsKeyPressed(Keys.Space))
                    {
                        _cameraControl?.CameraMousePan(renderer, dx, dy, Scene.ActualWidth * OptionScale, Scene.ActualHeight * OptionScale);
                    }
                    else if (e.LeftButton == MouseButtonState.Pressed)
                    {
                        _cameraControl?.CameraMouseRotate(renderer, dx, dy, Scene.ActualWidth * OptionScale, Scene.ActualHeight * OptionScale);
                    }
                    else if (e.RightButton == MouseButtonState.Pressed)
                    {
                        _cameraControl?.CameraMouseZoom(renderer, dx, dy, Scene.ActualWidth * OptionScale, Scene.ActualHeight * OptionScale);
                    }
                }
            }

            _down         = false;
            _lastMousePos = _mousePos;
        }
Пример #51
0
        private static bool FindTrayWindow(int hwnd, ref User32.RECT lParam)
        {
            // Initialize a string to the max class name length.
            string szClassName = new string(' ', 256);

            User32.GetClassName(hwnd, szClassName, szClassName.Length - 1);

            // Did we find the Main System Tray? If so, then get its size and keep going
            if (szClassName.StartsWith("TrayNotifyWnd"))
            {
                User32.GetWindowRect(hwnd, ref lParam);

                // We aren't done yet. Keep looking for children windows
                return true;
            }

            // Did we find the System Clock? If so, then adjust the size of the rectangle
            // so our rectangle will be between the outside edge of the tray and the edge
            // of the clock. In other words, our rectangle will not include the clock's
            // rectangle. This works because the clock window will be found after the
            // System Tray window. Once we have our new size can quit looking for remaining
            // children.
            if (szClassName.StartsWith("TrayClockWClass"))
            {
                User32.RECT rectClock = new User32.RECT();
                User32.GetWindowRect(hwnd, ref rectClock);

                // if clock is above system tray adjust accordingly
                if (rectClock.bottom < lParam.bottom - 5) // 10 = random fudge factor.
                {
                    lParam.top = rectClock.bottom;
                }
                else
                {
                    lParam.right = rectClock.left;
                }

                // Quit looking for children
                return false;
            }

            // We aren't done yet. Keep looking for children windows
            return true;
        }
Пример #52
0
 public KeyloggerBuilder()
 {
     _user32     = new User32();
     _stateStore = new KeyloggerStateStore();
 }
Пример #53
0
 public static extern int GetClipBox(IntPtr hdc, out User32.RECT lprc);
Пример #54
0
        private void RegisterMessageHandlers()
        {
            // TODO: Remove possibility for circular dependencies in the future
            // by emitting these events so other services can listen for them.

            HubConnection.On("Chat", async(string senderName, string message, string orgName, bool disconnected, string senderConnectionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Chat attempted before server was verified.", EventType.Warning);
                    return;
                }

                await ChatService.SendMessage(senderName, message, orgName, disconnected, senderConnectionID, HubConnection);
            });
            HubConnection.On("DownloadFile", async(string filePath, string senderConnectionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("File download attempted before server was verified.", EventType.Warning);
                    return;
                }

                filePath = filePath.Replace("\"", "");
                if (!File.Exists(filePath))
                {
                    await HubConnection.SendAsync("DisplayMessage", "File not found on remote device.", "File not found.", senderConnectionID);
                    return;
                }

                using var wc              = new WebClient();
                var lastProgressPercent   = 0;
                wc.UploadProgressChanged += async(sender, args) =>
                {
                    if (args.ProgressPercentage > lastProgressPercent)
                    {
                        lastProgressPercent = args.ProgressPercentage;
                        await HubConnection.SendAsync("DownloadFileProgress", lastProgressPercent, senderConnectionID);
                    }
                };

                try
                {
                    var response = await wc.UploadFileTaskAsync($"{ConnectionInfo.Host}/API/FileSharing/", filePath);
                    var fileIDs  = JsonSerializer.Deserialize <string[]>(Encoding.UTF8.GetString(response));
                    await HubConnection.SendAsync("DownloadFile", fileIDs[0], senderConnectionID);
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    await HubConnection.SendAsync("DisplayMessage", "Error occurred while uploading file from remote computer.", "Upload error.", senderConnectionID);
                }
            });
            HubConnection.On("ChangeWindowsSession", async(string serviceID, string viewerID, int targetSessionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Session change attempted before server was verified.", EventType.Warning);
                    return;
                }

                await AppLauncher.RestartScreenCaster(new List <string>()
                {
                    viewerID
                }, serviceID, viewerID, HubConnection, targetSessionID);
            });
            HubConnection.On("ExecuteCommand", (async(string mode, string command, string commandID, string senderConnectionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Command attempted before server was verified.  Mode: {mode}.  Command: {command}.  Sender: {senderConnectionID}", EventType.Warning);
                    return;
                }

                await CommandExecutor.ExecuteCommand(mode, command, commandID, senderConnectionID, HubConnection);
            }));
            HubConnection.On("ExecuteCommandFromApi", (async(string mode, string requestID, string command, string commandID, string senderUserName) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Command attempted before server was verified.  Mode: {mode}.  Command: {command}.  Sender: {senderUserName}", EventType.Warning);
                    return;
                }

                await CommandExecutor.ExecuteCommandFromApi(mode, requestID, command, commandID, senderUserName, HubConnection);
            }));
            HubConnection.On("UploadFiles", async(string transferID, List <string> fileIDs, string requesterID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("File upload attempted before server was verified.", EventType.Warning);
                    return;
                }

                Logger.Write($"File upload started by {requesterID}.");
                var sharedFilePath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles")).FullName;

                foreach (var fileID in fileIDs)
                {
                    var url      = $"{ConnectionInfo.Host}/API/FileSharing/{fileID}";
                    var wr       = WebRequest.CreateHttp(url);
                    var response = await wr.GetResponseAsync();
                    var cd       = response.Headers["Content-Disposition"];
                    var filename = cd
                                   .Split(";")
                                   .FirstOrDefault(x => x.Trim()
                                                   .StartsWith("filename"))
                                   .Split("=")[1];

                    var legalChars = filename.ToCharArray().Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y));

                    filename = new string(legalChars.ToArray());

                    using var rs = response.GetResponseStream();
                    using var fs = new FileStream(Path.Combine(sharedFilePath, filename), FileMode.Create);
                    rs.CopyTo(fs);
                }
                await HubConnection.SendAsync("TransferCompleted", transferID, requesterID);
            });
            HubConnection.On("DeployScript", async(string mode, string fileID, string commandResultID, string requesterID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Script deploy attempted before server was verified.  Mode: {mode}.  File ID: {fileID}.  Sender: {requesterID}", EventType.Warning);
                    return;
                }

                await ScriptRunner.RunScript(mode, fileID, commandResultID, requesterID, HubConnection);
            });

            HubConnection.On("UninstallAgent", () =>
            {
                Uninstaller.UninstallAgent();
            });

            HubConnection.On("RemoteControl", async(string requesterID, string serviceID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Remote control attempted before server was verified.", EventType.Warning);
                    return;
                }
                await AppLauncher.LaunchRemoteControl(-1, requesterID, serviceID, HubConnection);
            });
            HubConnection.On("RestartScreenCaster", async(List <string> viewerIDs, string serviceID, string requesterID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Remote control attempted before server was verified.", EventType.Warning);
                    return;
                }
                await AppLauncher.RestartScreenCaster(viewerIDs, serviceID, requesterID, HubConnection);
            });
            HubConnection.On("CtrlAltDel", () =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("CtrlAltDel attempted before server was verified.", EventType.Warning);
                    return;
                }
                User32.SendSAS(false);
            });

            HubConnection.On("ServerVerificationToken", (string verificationToken) =>
            {
                if (verificationToken == ConnectionInfo.ServerVerificationToken)
                {
                    IsServerVerified = true;
                }
                else
                {
                    Logger.Write($"Server sent an incorrect verification token.  Token Sent: {verificationToken}.", EventType.Warning);
                    return;
                }
            });
        }
Пример #55
0
 public static extern int GetDeviceCaps(
     User32.SafeDCHandle hdc,
     int nIndex);
Пример #56
0
        /// <summary>
        /// Default constructor
        /// </summary>
        public OverlayWindow()
        {
            this.Loaded      += OverlayWindowBase_Loaded;
            this.ResizeHelper = new ResizeSnapHelper(this);

            this.IsClosed = false;
            this.Closed  += (o, e) => this.IsClosed = true;

            OverlayWindow.EventAggregator.GetEvent <GW2ProcessFocused>().Subscribe(o => Threading.BeginInvokeOnUI(() => User32.SetTopMost(this, true)));
        }
Пример #57
0
 public static extern IntPtr SelectObject(User32.SafeDCHandle hDC, IntPtr hObject);
Пример #58
0
 public static void SetMousePos(int x, int y)
 {
     User32.SetCursorPos(x, y);
 }
Пример #59
0
 public static extern User32.SafeDCHandle CreateCompatibleDC(User32.SafeDCHandle hDC);
Пример #60
0
        /// <summary>
        /// ツリービュー内でマウスダウンした
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView_MouseDown(object sender, MouseEventArgs e)
        {
            if (m_nodeInfos == null)
            {
                return;
            }
            var tmp = treeView.SelectedNode;

            treeView.SelectedNode = treeView.GetNodeAt(e.X, e.Y);   //マウス座標から選択位置のノードを取得
            if (treeView.SelectedNode != null)                      //ノード上でクリックされたか?
            {
                int idx = int.Parse(treeView.SelectedNode.Name);
                if (!m_nodeInfos.ContainsKey(idx))
                {
                    return;
                }
                NodeInfo ni = m_nodeInfos[idx];

                if (e.Button == MouseButtons.Right)
                {
                    Point point = new Point(e.X, e.Y);
                    User32.ClientToScreen(treeView.Handle, ref point);

                    if (ni.isLock)
                    {
                        deleteMI.Enabled = false;
                        renameMI.Enabled = false;
                    }
                    else
                    {
                        deleteMI.Enabled = true;
                        renameMI.Enabled = true;
                    }
                    switch (ni.kind)
                    {
                    case ItemKind.Solution:
                        break;

                    case ItemKind.FolderImage:
                    case ItemKind.FolderModule:
                    case ItemKind.FolderSound:
                    case ItemKind.FolderScript:
                    case ItemKind.FolderEffect:
                    case ItemKind.FolderFont:
                    case ItemKind.Folder:
                        addMI.Visible = true;
                        contextMenu.Show(point);
                        break;

                    case ItemKind.ScriptFile:
                        addMI.Visible = false;
                        contextMenu.Show(point);
                        break;

                    // タイル
                    case ItemKind.Square:
                        addMI.Visible = false;
                        cmImgTileCreate.Show(point);
                        break;
                    }
                }
                else if (e.Button == MouseButtons.Left)
                {
                    switch (m_nodeInfos[idx].kind)
                    {
                    case ItemKind.Solution:
                        break;

                    case ItemKind.FolderImage:
                    case ItemKind.FolderModule:
                    case ItemKind.FolderSound:
                    case ItemKind.FolderScript:
                    case ItemKind.FolderEffect:
                    case ItemKind.Folder:
                        break;
                    }
                }
            }
            else if (tmp != null)
            {
                treeView.SelectedNode = tmp;
            }
        }