示例#1
0
        internal void Reload(string path, string searchPattern, FileDialogBehavior behavior)
        {
            this.Items.Clear();

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            string solvedPath = path;

            FileInfo fileInfo = new FileInfo(path);

            if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
            {
                solvedPath = WinApi.GetReparsePointFileName(path);
            }

            DirectoryInfo parentDirectory = Directory.GetParent(path);

            if (parentDirectory != null)
            {
                this.Items.Add(new FileDialogItem(FileDialogItemType.Directory, "..", parentDirectory.FullName));
            }

            try
            {
                ReloadDirectories(solvedPath, behavior);
                ReloadFiles(solvedPath, searchPattern, behavior);
            }
            catch (Exception ex)
            {
                this.Items.Add(new FileDialogItem(FileDialogItemType.Directory, ex.Message, string.Empty));
            }

            this.OnCollectionChanged(new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Reset));
        }
示例#2
0
        public static LoginInformation AuthWindows(string username, string password)
        {
            var info = new LoginInformation();

            try
            {
                var domainName = Environment.UserDomainName;
                if (username.IsValidEmail())
                {
                    domainName = "MicrosoftAccount";
                }
                if (username.Contains("\\"))
                {
                    var splitName = username.Split('\\');
                    domainName = splitName[0];
                    username   = splitName[1];
                }
                using (var wim = new WindowsIdentityImpersonator(domainName, username, password))
                {
                    wim.BeginImpersonate();
                    {
                        info.IsAdmin  = WinApi.IsAdministratorByToken(WindowsIdentity.GetCurrent());
                        info.LoggedIn = true;
                        info.Message  = $"Logged in successfully as {username}";
                    }
                    wim.EndImpersonate();
                }
            }
            catch (Exception ex)
            {
                info.IsAdmin  = false;
                info.LoggedIn = false;
                info.Message  = ex.Message;
            }
            return(info);
        }
示例#3
0
        /// <summary>
        /// This method disconnects the class from the shared memory block and if this
        /// is the last instance referencing the block, then the block will be
        /// deleted.  Note that it's OK to call Close() even if the object isn't
        /// currently open.  This method is thread safe.
        /// </summary>
        public void Close()
        {
            lock (syncLock)
            {
                if (m_hMap == IntPtr.Zero)
                {
                    return;
                }

                // Unlock the memory

                if (m_pvBlock != null)
                {
                    while (m_cLock > 0)
                    {
                        Unlock();
                    }
                }

                // Free the map

                if (m_hMap != IntPtr.Zero)
                {
#if SHAREDMEM_DRIVER
                    WinApi.MEM_Close(m_hMap);
#else
                    WinApi.CloseHandle(m_hMap);
#endif
                    m_hMap = IntPtr.Zero;
                }

                // Free the mutex

                m_mutex.Close();
            }
        }
示例#4
0
        /// <summary>
        /// 将窗体内置到面板工作区中,设置窗体大小自适应、面板和窗体互相关闭
        /// </summary>
        /// <param name="form"></param>
        /// <param name="dockPanel"></param>
        private void FormIntoDockPanel(Form form, DockPanel dockPanel)
        {
            //将窗体内置到面板工作区中
            int dockPanelWnd = dockPanel.ControlContainer.Handle.ToInt32();

            WinApi.SetParent(form.Handle.ToInt32(), dockPanelWnd);
            OnResize(dockPanelWnd, form.Handle, 4, 3);

            //窗体自适应停靠面板大小
            dockPanel.ControlContainer.SizeChanged += (sender, e) => OnResize(dockPanelWnd, form.Handle, 4, 3);

            //关闭面板时关闭窗体
            dockPanel.ClosingPanel += (sender, e) =>
            {
                if (!IsCloseDockPanel)
                {
                    dockPanel.Hide();
                    return;
                }
                if (!form.IsDisposed && IsCloseDockPanel)
                {
                    form.Close();
                }
                if (!form.IsDisposed)
                {
                    e.Cancel = true;
                }
            };

            //关闭窗体时关闭面板
            form.FormClosed += (sender, e) =>
            {
                FloatLocation = dockPanel.FloatLocation;
                dockManager1.RemovePanel(dockPanel);
            };
        }
示例#5
0
        protected override bool InsertUnlessFull(int index, TKey key, TValue value)
        {
            if (RecordCount >= m_maxRecordsPerNode)
            {
                return(false);
            }

            byte *start = GetWritePointerAfterHeader() + index * KeyValueSize;

            if (index != RecordCount)
            {
                WinApi.MoveMemory(start + KeyValueSize, start, (RecordCount - index) * KeyValueSize);
            }

            //Insert the data

            m_encoding.Encode(start, null, null, key, value);
            //key.Write(start);
            //value.Write(start + KeySize);

            //save the header
            IncrementOneRecord(KeyValueSize);
            return(true);
        }
        public HiddenWindowMessages()
        {
            messageHooks = new List <HwndSourceHook>();

            //generate a unique ID for the window
            WindowId = "WClipboard_" + Guid.NewGuid();

            //register window message handler
            messageHandler = OnWindowMessageReceived;

            // Create a simple window class which is reference through
            //the messageHandler delegate
            WindowClass wc;

            wc.style         = 0;
            wc.lpfnWndProc   = messageHandler;
            wc.cbClsExtra    = 0;
            wc.cbWndExtra    = 0;
            wc.hInstance     = IntPtr.Zero;
            wc.hIcon         = IntPtr.Zero;
            wc.hCursor       = IntPtr.Zero;
            wc.hbrBackground = IntPtr.Zero;
            wc.lpszMenuName  = string.Empty;
            wc.lpszClassName = WindowId;

            // Register the window class
            WinApi.RegisterClass(ref wc);

            // Create the message window
            Handle = WinApi.CreateWindowEx(0, WindowId, "", 0, 0, 0, 1, 1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

            if (Handle == IntPtr.Zero)
            {
                throw new Win32Exception("Message window handle was not a valid pointer");
            }
        }
        public override void Render()
        {
            base.Render();
            if (!Settings.Enable || WinApi.IsKeyDown(Keys.F10) ||
                !Settings.ShowInTown && GameController.Area.CurrentArea.IsTown ||
                !Settings.ShowInTown && GameController.Area.CurrentArea.IsHideout)
            {
                return;
            }

            List <EntityWrapper> deadEntities = aliveEntities.Where(entity => !entity.IsAlive).ToList();

            foreach (EntityWrapper entity in deadEntities)
            {
                Calc(entity);
                aliveEntities.Remove(entity);
            }

            Vector2 position = StartDrawPointFunc();
            var     size     = new Size2();

            if (Settings.ShowDetail)
            {
                size = DrawCounters(position);
            }
            var   session = $"({sessionCounter + summaryCounter})";
            Size2 size2   = Graphics.DrawText($"kills: {summaryCounter} {session}",
                                              Settings.KillsTextSize, position.Translate(0, size.Height), Settings.TextColor, FontDrawFlags.Right);
            int width  = Math.Max(size.Width, size2.Width);
            var bounds = new RectangleF(position.X - width - 46, position.Y - 5, width + 50, size.Height + size2.Height + 10);

            Graphics.DrawImage("preload-start.png", bounds, Settings.BackgroundColor);
            Graphics.DrawImage("preload-end.png", bounds, Settings.BackgroundColor);
            Size   = bounds.Size;
            Margin = new Vector2(0, 5);
        }
示例#8
0
        /// <summary>
        /// Feeds a click generated on the mouse hook
        /// </summary>
        /// <param name="e"></param>
        internal static bool FeedHookClick(MouseEventArgs e)
        {
            //Al-74 fix (see GitHub issue #10):
            //Starting from Windows 10 April 2018 Update (version 1803) with display scaling above 100%, e.Location is the physical mouse location,
            //not scaled according to display scaling, so the Contains function fails check and no events fires when clicking RibbonButtons dropdown items.
            //Use GetCursorPos api instead of e.Location seems to solve the problem.

            WinApi.POINT pos;
            if (WinApi.GetCursorPos(out pos))
            {
                foreach (RibbonPopup p in pops)
                {
                    if (p.WrappedDropDown.Bounds.Contains(pos.x, pos.y))
                    //if (p.WrappedDropDown.Bounds.Contains(e.Location))
                    {
                        return(true);
                    }
                }
            }

            //If click was in no dropdown, let's go everyone
            Dismiss(DismissReason.AppClicked);
            return(false);
        }
示例#9
0
        private FREObject Capture(FREContext ctx, uint argc, FREObject[] argv)
        {
            var rect = new WinApi.Rect();

            WinApi.GetWindowRect(_webViewWindow, ref rect);
            var x      = 0;
            var y      = 0;
            var width  = rect.right - rect.left;
            var height = rect.bottom - rect.top;

            try {
                var freCropTo = argv[0];
                if (freCropTo != FREObject.Zero)
                {
                    var cropTo = freCropTo.AsRect();
                    x = Convert.ToInt32(cropTo.X);
                    y = Convert.ToInt32(cropTo.Y);
                    var freW = Convert.ToInt32(cropTo.Width);
                    var freH = Convert.ToInt32(cropTo.Height);
                    width  = freW > 0 ? freW : width;
                    height = freH > 0 ? freH : height;
                }

                _capturedBitmapData = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                var graphics = Graphics.FromImage(_capturedBitmapData);
                graphics.CopyFromScreen(rect.left + x, rect.top + y, 0, 0, new Size(width, height),
                                        CopyPixelOperation.SourceCopy);

                DispatchEvent(OnCaptureComplete, "");
            }
            catch (Exception e) {
                return(new FreException(e).RawValue);
            }

            return(FREObject.Zero);
        }
示例#10
0
        /// <summary>
        /// 开始模拟鼠标操作桌面微信,(微信聊天列表不能有置顶聊天)
        /// </summary>
        public void StartSimulateWeChat()
        {
            IntPtr awin = WinApi.GetWeChatWindow();

            if (awin == IntPtr.Zero)
            {
                MessageBox.Show("获取微信主窗口句柄失败", "提示");
                return;
            }
            WinApi.CloseWindow(awin);
            WinApi.ShowWindow(awin, WinApi.NCmdShowFlag.SW_SHOWNORMAL);//在显示
            RECT rc = new RECT();

            WinApi.GetWindowRect(awin, ref rc);
            endPosition.X = rc.Left;
            endPosition.Y = rc.Top;
            if (true)
            {
                //应该打开窗口有延迟,所以需要定时去操作
                ////暂停2秒
                Thread.Sleep(2000);
                moveMouseToWeChatSeachBox(endPosition);
            }
        }
示例#11
0
文件: Manager.cs 项目: wyrover/ospy
        private void DoInjection()
        {
            handles = new UIntPtr[processes.Length];

            try
            {
                // Inject into the desired process IDs
                for (int i = 0; i < processes.Length; i++)
                {
                    int percentComplete = (int)(((float)(i + 1) / (float)processes.Length) * 100.0f);
                    progress.ProgressUpdate("Injecting logging agents", percentComplete);
                    handles[i] = InjectDll(processes[i].Id);
                }
            }
            catch
            {
                // Roll back if needed
                for (int i = 0; i < handles.Length; i++)
                {
                    if (handles[i] != UIntPtr.Zero)
                    {
                        try
                        {
                            UnInjectDll(processes[i].Id, handles[i]);
                        }
                        catch
                        {
                        }
                    }
                }

                throw;
            }

            WinApi.SetEvent(startReqEvent);
        }
示例#12
0
        public override bool IsTransitionAvailable(out string availableState)
        {
            availableTransitionState = StateName;
            availableState           = StateName;

            if (!main.IsTimerPausedByUser() && main.InputReceivedThisTick)
            {
                string titlee = WinApi.GetWindowTitle().ToString().ToLowerInvariant();
                if (!main.IsTitleSameTitleAsPrevious(titlee))
                {
                    if (main.IsTitleValidWindowTitleCapture(titlee))
                    {
                        if (Data.Settings.Blacklist.IsTitleAllowed(titlee, out BlacklistItem blacklistItem))
                        {
                            availableTransitionState = "Resumed";
                            availableState           = "Resumed";
                            //main.ArtistResume.Execute(null);
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
示例#13
0
        public CVP(string path, float scale = 1)
        {
            vReader = new VideoFileReader();
            vReader.Open(path);

            consoleFontSize = Util.GetConsoleFontSize();
            totalFrames     = vReader.FrameCount;

            this.scale = scale;
            if (Math.Abs(scale - 1) > 1e-6)
            {
                shouldRescale = true;
            }
            if (shouldRescale)
            {
                vidSize = new Size((int)(vReader.Width * scale), (int)(vReader.Height * scale));
            }
            else
            {
                vidSize = new Size(vReader.Width, vReader.Height);
            }
            consoleSize = vidSize + new Size(consoleFontSize.Width * 2 - 1, consoleFontSize.Height * 4);

            Util.FixConsoleWindowSize();
            Util.AdjustConsoleWindowSize(consoleSize);
            Console.SetBufferSize(Console.WindowWidth, Console.WindowHeight);

            vidPos        = new Point(0, consoleFontSize.Height);
            fr            = vReader.FrameRate;
            frRnd         = (int)Math.Round(fr.Value);
            ticksPerFrame = (long)(1e7 / fr.Value);
            playThread    = new Thread(InternalPlay);
            workThread    = new Thread(PreloadFrames);

            g = Graphics.FromHwnd(WinApi.GetConsoleWindow());
        }
示例#14
0
        public static Client OpenMC(string path, string arguments)
        {
            var fileVersion = FileVersionInfo.GetVersionInfo(path).FileVersion;
            var version     = ClientVersion.GetFromFileVersion(fileVersion);

            if (version == null)
            {
                throw new Exception("The version " + fileVersion + " is not supported.");
            }

            WinApi.PROCESS_INFORMATION pi = new WinApi.PROCESS_INFORMATION();
            WinApi.STARTUPINFO         si = new WinApi.STARTUPINFO();

            if (arguments == null)
            {
                arguments = "";
            }

            WinApi.CreateProcess(path, " " + arguments, IntPtr.Zero, IntPtr.Zero, false, WinApi.CREATE_SUSPENDED, IntPtr.Zero, Path.GetDirectoryName(path), ref si, out pi);

            Process p = Process.GetProcessById(Convert.ToInt32(pi.dwProcessId));

            var client = new Client(p, version, Path.GetDirectoryName(path));

            Memory.WriteByte(client.ProcessHandle, client.MemoryAddresses.ClientMultiClient, client.MemoryAddresses.ClientMultiClientJMP);

            WinApi.ResumeThread(pi.hThread);
            p.WaitForInputIdle();

            Memory.WriteByte(client.ProcessHandle, client.MemoryAddresses.ClientMultiClient, client.MemoryAddresses.ClientMultiClientJNZ);

            WinApi.CloseHandle(pi.hProcess);
            WinApi.CloseHandle(pi.hThread);

            return(client);
        }
示例#15
0
        protected void NotifyNotDetectableWindows()
        {
            try
            {
                var windowsToNotify = new List <IntPtr>();

                foreach (ProcessThread thread in pokerClientProcess.Threads)
                {
                    WinApi.EnumThreadWindows(thread.Id, (hWnd, lParam) =>
                    {
                        var sb = new StringBuilder(256);

                        if (hWnd != IntPtr.Zero && WinApi.GetClassName(hWnd, sb, sb.Capacity) != 0 &&
                            sb.ToString().Contains(WindowClassName))
                        {
                            var windowTitle = WinApi.GetWindowText(hWnd);

                            var titleInfo = new IgnitionTableTitle(windowTitle);

                            if (titleInfo.IsValid && !titleInfo.IsZone)
                            {
                                windowsToNotify.Add(hWnd);
                            }
                        }

                        return(true);
                    }, IntPtr.Zero);
                }

                NotifyNotDetectableWindows(windowsToNotify);
            }
            catch (Exception e)
            {
                LogProvider.Log.Error(this, $"Could not notify not detectable windows. [{Identifier}]", e);
            }
        }
        private void FindUpDown()
        {
            bool bFound = false;

            IntPtr pWnd = WinApi.GetWindow(Handle, WinApi.GW_CHILD);

            while (pWnd != IntPtr.Zero)
            {
                char[] className = new char[33];

                int length = WinApi.GetClassName(pWnd, className, 32);

                string s = new string(className, 0, length);

                if (s == "msctls_updown32")
                {
                    bFound = true;

                    if (!bUpDown)
                    {
                        this.scUpDown = new SubClass(pWnd, true);
                        this.scUpDown.SubClassedWndProc += new SubClass.SubClassWndProcEventHandler(scUpDown_SubClassedWndProc);

                        bUpDown = true;
                    }
                    break;
                }

                pWnd = WinApi.GetWindow(pWnd, WinApi.GW_HWNDNEXT);
            }

            if ((!bFound) && (bUpDown))
            {
                bUpDown = false;
            }
        }
示例#17
0
        /// <summary>
        /// This method releases the lock on the shared memory block.  This method
        /// is threadsafe.
        /// </summary>
        public void Unlock()
        {
            Assertion.Test(m_hMap != IntPtr.Zero);
            Assertion.Test(m_mutex != null);
            Assertion.Test(m_cLock != 0);
            Assertion.Test(m_pvBlock != null);

            if (m_cLock == 0)
            {
                return;
            }

            m_cLock--;
            if (m_cLock == 0)
            {
#if SHAREDMEM_DRIVER
                WinApi.MEM_Unlock(m_hMap, m_cbBlock);
#else
                WinApi.UnmapViewOfFile(m_pvBlock);
#endif
            }

            m_mutex.ReleaseMutex();
        }
示例#18
0
        private void Render()
        {
            var screenDc = WinApi.GetDC(WinApi.NullHandleRef);

            if (screenDc == IntPtr.Zero)
            {
                return;
            }
            try {
                var memDc = WinApi.CreateCompatibleDC(new HandleRef(null, screenDc));
                if (memDc == IntPtr.Zero)
                {
                    return;
                }
                try {
                    using (Bitmap bmp = GetWindowBitmap(Size.Width, Size.Height)) {
                        IntPtr hBitmap    = bmp.GetHbitmap(_transparent);
                        IntPtr hOldBitmap = WinApi.SelectObject(memDc, hBitmap);

                        WinApi.POINT newLocation = new WinApi.POINT(Location);
                        WinApi.SIZE  newSize     = new WinApi.SIZE(Size);
                        WinApi.UpdateLayeredWindow(Handle, screenDc, ref newLocation, ref newSize, memDc, ref _ptZero, 0, ref _blend, WinApi.BlendingFlags.ULW_ALPHA);

                        if (hBitmap != IntPtr.Zero)
                        {
                            WinApi.SelectObject(memDc, hOldBitmap);
                            WinApi.DeleteObject(hBitmap);
                        }
                    }
                } finally {
                    WinApi.DeleteDC(new HandleRef(null, memDc));
                }
            } finally {
                WinApi.ReleaseDC(WinApi.NullHandleRef, new HandleRef(null, screenDc));
            }
        }
示例#19
0
        private void UpdateAppBarState()
        {
            if (_suppressingUIToSysUpdate)
            {
                return;
            }

            var autohide    = ChkAutoHide.Checked;
            var alwaysOnTop = ChkAlwaysOnTop.Checked;

            var abd = new WinApi.APPBARDATA();

            abd.hWnd = _taskBarHwnd;
            if (autohide)
            {
                abd.lParam = (int)(alwaysOnTop ? WinApi.ABState.ABS_AUTOHIDEANDONTOP : WinApi.ABState.ABS_AUTOHIDE);
            }
            else
            {
                abd.lParam = (int)(alwaysOnTop ? WinApi.ABState.ABS_ALWAYSONTOP : WinApi.ABState.ABS_MANUAL);
            }

            WinApi.SHAppBarMessage((uint)WinApi.ABMsg.ABM_SETSTATE, ref abd);
        }
示例#20
0
 /// <summary>
 /// Handles the EXCEPTION_DATATYPE_MISALIGNMENT debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnDatatypeMisalignmentDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#21
0
 /// <summary>
 /// Handles the EXCEPTION_BREAKPOINT debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnBreakpointDebugException(ref WinApi.DEBUG_EVENT de)
 {
     if (!this.InitialBreakpointHit)
     {
         this.InitialBreakpointHit = true;
         return WinApi.DbgCode.CONTINUE;
     }
     else
     {
         return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
     }
 }
示例#22
0
 /// <summary>
 /// Handles the EXCEPTION_ARRAY_BOUNDS_EXCEEDED debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnArrayBoundsExceededDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#23
0
 /// <summary>
 /// Handles the EXCEPTION_ACCESS_VIOLATION debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnAccessViolationDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#24
0
 /// <summary>
 /// Handles the RIP_EVENT debug event.
 /// </summary>
 /// <param name="de">The debug event that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnRipEvent(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.CONTINUE;
 }
示例#25
0
        public override void Render()
        {
            if (!holdKey && WinApi.IsKeyDown(Keys.F10))
            {
                holdKey = true;
                Settings.Enable.Value = !Settings.Enable.Value;
                SettingsHub.Save(settingsHub);
            }
            else if (holdKey && !WinApi.IsKeyDown(Keys.F10))
            {
                holdKey = false;
            }
            if (!Settings.Enable)
            {
                return;
            }

            if (Settings.Enable)
            {
                Positioned pos = GameController.Player.GetComponent <Positioned>();
                if (pos == null)
                {
                    return;
                }
                Vector2   playerPos     = pos.GridPos;
                Vector2   position      = StartDrawPointFunc();
                const int BOTTOM_MARGIN = 2;
                bool      shouldUpdate  = false;

                if (Settings.BorderSettings.Enable)
                {
                    Dictionary <EntityWrapper, AlertDrawStyle> tempCopy = new Dictionary <EntityWrapper, AlertDrawStyle>(currentAlerts);
                    var keyValuePairs = tempCopy.AsParallel().Where(x => x.Key != null && x.Key.Address != 0 && x.Key.IsValid).ToList();
                    foreach (var kv in keyValuePairs)
                    {
                        if (DrawBorder(kv.Key.Address) && !shouldUpdate)
                        {
                            shouldUpdate = true;
                        }
                    }
                }

                foreach (KeyValuePair <EntityWrapper, AlertDrawStyle> kv in currentAlerts.Where(x => x.Key != null && x.Key.Address != 0 && x.Key.IsValid))
                {
                    string text = GetItemName(kv);
                    if (text == null)
                    {
                        continue;
                    }

                    ItemsOnGroundLabelElement entityLabel;
                    if (!currentLabels.TryGetValue(kv.Key.Address, out entityLabel))
                    {
                        shouldUpdate = true;
                    }
                    else
                    {
                        if (Settings.ShowText && (!Settings.HideOthers || entityLabel.CanPickUp || entityLabel.MaxTimeForPickUp.TotalSeconds == 0))
                        {
                            position = DrawText(playerPos, position, BOTTOM_MARGIN, kv, text);
                        }
                    }
                }
                Size = new Size2F(0, position.Y); //bug absent width

                if (shouldUpdate)
                {
                    currentLabels = GameController.Game.IngameState.IngameUi.ItemsOnGroundLabels
                                    .GroupBy(y => y.ItemOnGround.Address).ToDictionary(y => y.Key, y => y.First());
                }
            }
        }
示例#26
0
 private void MoveControl()
 {
     WinApi.ReleaseCapture();
     WinApi.SendMessage(Handle, (int)WinApi.Messages.WM_NCLBUTTONDOWN, (int)WinApi.HitTest.HTCAPTION, 0);
 }
示例#27
0
 /// <summary>
 /// Handles the EXCEPTION_PRIV_INSTRUCTION debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnPrivInstructionDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#28
0
 private void p_Title_MouseDown(object sender, MouseEventArgs e)
 {
     WinApi.ReleaseCapture();
     WinApi.SendMessage(this.Handle, WinApi.WM_SYSCOMMAND, WinApi.SC_MOVE + WinApi.HTCAPTION, 0);
 }
示例#29
0
        /// <summary>
        /// Processes mouse events, which are bubbled
        /// through the class' routed events, trigger
        /// certain actions (e.g. show a popup), or
        /// both.
        /// </summary>
        /// <param name="me">Event flag.</param>
        private void OnMouseEvent(MouseEvent me)
        {
            if (this.IsDisposed)
            {
                return;
            }

            switch (me)
            {
            case MouseEvent.MouseMove:
                this.RaiseTrayMouseMoveEvent();
                //immediately return - there's nothing left to evaluate
                return;

            case MouseEvent.IconRightMouseDown:
                this.RaiseTrayRightMouseDownEvent();
                break;

            case MouseEvent.IconLeftMouseDown:
                this.RaiseTrayLeftMouseDownEvent();
                break;

            case MouseEvent.IconRightMouseUp:
                this.RaiseTrayRightMouseUpEvent();
                break;

            case MouseEvent.IconLeftMouseUp:
                this.RaiseTrayLeftMouseUpEvent();
                break;

            case MouseEvent.IconMiddleMouseDown:
                this.RaiseTrayMiddleMouseDownEvent();
                break;

            case MouseEvent.IconMiddleMouseUp:
                this.RaiseTrayMiddleMouseUpEvent();
                break;

            case MouseEvent.IconDoubleClick:
                //cancel single click timer
                this.singleClickTimer.Change(Timeout.Infinite, Timeout.Infinite);
                //bubble event
                this.RaiseTrayMouseDoubleClickEvent();
                break;

            case MouseEvent.BalloonToolTipClicked:
                this.RaiseTrayBalloonTipClickedEvent();
                break;
                //default:
                //    throw new ArgumentOutOfRangeException("me", "Missing handler for mouse event flag: " + me);
            }


            //get mouse coordinates
            Point cursorPosition = new Point();

            if (messageSink.Version == NotifyIconVersion.Vista)
            {
                //physical cursor position is supported for Vista and above
                WinApi.GetPhysicalCursorPos(ref cursorPosition);
            }
            else
            {
                WinApi.GetCursorPos(ref cursorPosition);
            }

            cursorPosition = this.GetDeviceCoordinates(cursorPosition);

            bool isLeftClickCommandInvoked = false;

            //show popup, if requested
            if (me.IsMatch(this.PopupActivation))
            {
                if (me == MouseEvent.IconLeftMouseUp)
                {
                    //show popup once we are sure it's not a double click
                    singleClickTimerAction = () =>
                    {
                        this.LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
                        this.ShowTrayPopup(cursorPosition);
                    };

                    this.singleClickTimer.Change(WinApi.GetDoubleClickTime(), Timeout.Infinite);
                    isLeftClickCommandInvoked = true;
                }
                else
                {
                    //show popup immediately
                    this.ShowTrayPopup(cursorPosition);
                }
            }


            //show context menu, if requested
            if (me.IsMatch(this.MenuActivation))
            {
                if (me == MouseEvent.IconLeftMouseUp)
                {
                    //show context menu once we are sure it's not a double click
                    singleClickTimerAction = () =>
                    {
                        LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
                        ShowContextMenu(cursorPosition);
                    };
                    singleClickTimer.Change(WinApi.GetDoubleClickTime(), Timeout.Infinite);
                    isLeftClickCommandInvoked = true;
                }
                else
                {
                    //show context menu immediately
                    ShowContextMenu(cursorPosition);
                }
            }

            //make sure the left click command is invoked on mouse clicks
            if (me == MouseEvent.IconLeftMouseUp && !isLeftClickCommandInvoked)
            {
                //show context menu once we are sure it's not a double click
                this.singleClickTimerAction = () =>
                {
                    this.LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
                };

                this.singleClickTimer.Change(WinApi.GetDoubleClickTime(), Timeout.Infinite);
            }
        }
示例#30
0
 public bool FocusMe()
 {
     return(WinApi.SetForegroundWindow(Handle));
 }
 public void BeginUpdate()
 {
     WinApi.SendMessage(Handle, (int)WinApi.Messages.WM_SETREDRAW, false, 0);
     inUpdate = true;
 }
        public static void InputLoop()
        {
            uint        toRead            = 128;
            var         records           = new INPUT_RECORD[toRead];
            int         prevWidth         = MyConsole.Width;
            int         prevHeight        = MyConsole.Height;
            MouseButton prevMouseState    = MouseButton.None;
            COORD       prevMouseLocation = new COORD();

            while (!MyConsole.Exiting)
            {
                WinApi.ReadConsoleInput(inputHandle, records, toRead, out uint recordLen);

                for (int i = 0; i < recordLen; i++)
                {
                    var record = records[i];

                    switch (record.EventType)
                    {
                    case EventType.Mouse:
                    {
                        var mouseEvent = record.Event.MouseEvent;
                        var button     = mouseEvent.ButtonState;
                        var flags      = mouseEvent.EventFlags;
                        var location   = mouseEvent.MousePosition;

                        bool mousePressed  = prevMouseState == MouseButton.None && button != MouseButton.None;
                        bool mouseReleased = prevMouseState != MouseButton.None && button == MouseButton.None;
                        bool mouseHeld     = prevMouseState != MouseButton.None && button != MouseButton.None;

                        var args = new MouseEventArgs
                        {
                            Button          = button,
                            Location        = location,
                            ControlKeyState = mouseEvent.ControlKeyState
                        };

                        bool sameLocation = location.Equals(prevMouseLocation);

                        if (mousePressed && flags.HasFlag(MouseState.DoubleClick))
                        {
                            MouseDoubleClick?.Invoke(null, args);
                        }
                        else if (mousePressed)
                        {
                            MousePressed?.Invoke(null, args);
                        }
                        else if (mouseReleased)
                        {
                            MouseReleased?.Invoke(null, args);
                        }
                        else if (mouseHeld && flags.HasFlag(MouseState.Moved) && !sameLocation)
                        {
                            MouseDragged?.Invoke(null, args);
                        }
                        else if (flags.HasFlag(MouseState.Moved) && !sameLocation)
                        {
                            MouseMoved?.Invoke(null, args);
                        }

                        prevMouseState    = button;
                        prevMouseLocation = location;
                    }
                    break;

                    case EventType.Key:
                    {
                        var keyEvent = record.Event.KeyEvent;

                        var eventArgs = new KeyEventArgs
                        {
                            Key             = (ConsoleKey)keyEvent.VirtualKeyCode,
                            ControlKeyState = keyEvent.ControlKeyState
                        };

                        bool currState = keyEvent.KeyDown;
                        bool prevState = keyStates[keyEvent.VirtualKeyCode];

                        if (currState && !prevState)
                        {
                            KeyPressed?.Invoke(eventArgs);
                        }
                        else if (prevState && !currState)
                        {
                            KeyReleased?.Invoke(eventArgs);
                        }
                        else if (prevState && currState)
                        {
                            KeyHeld?.Invoke(eventArgs);
                        }

                        keyStates[keyEvent.VirtualKeyCode] = keyEvent.KeyDown;
                    }
                    break;

                    case EventType.Resize:
                    {
                        var clientSize = MyConsole.GetClientSize();
                        var fontSize   = MyConsole.GetFontSize();
                        int w          = clientSize.X / fontSize.X;
                        int h          = clientSize.Y / fontSize.Y;

                        if (prevWidth != w || prevHeight != h)
                        {
                            MyConsole.SetSize(w, h);
                            MyConsole.HideCursor();
                            Drawing.ConsoleRenderer.Resize(w, h);
                            Resized?.Invoke(new ResizedEventArgs
                                {
                                    Width  = w,
                                    Height = h
                                });
                            prevWidth  = w;
                            prevHeight = h;
                        }
                    }
                    break;

                    case EventType.Menu:
                    {
                        var id = record.Event.MenuEvent.dwCommandId;
                        Debug.WriteLine(id);
                    }
                    break;

                    case EventType.Focus:
                    {
                        var focused = record.Event.FocusEvent.bSetFocus;
                    }
                    break;

                    default:
                        Debug.WriteLine("Unhandled event: " + record.EventType);
                        break;
                    }
                }
            }
        }
示例#33
0
        private void DropToStash()
        {
            var cursorPosPreMoving = Mouse.GetCursorPosition();

            if (Settings.BlockInput.Value)
            {
                WinApi.BlockInput(true);
            }

            if (_dropItems.Count > 0)
            {
                // Dictionary where key is the index (stashtab index) and Value is the items to drop.
                var itemsToDrop = (from dropItem in _dropItems
                                   group dropItem by dropItem.StashNode.VisibleIndex
                                   into itemsToDropByTab
                                   select itemsToDropByTab).ToDictionary(tab => tab.Key, tab => tab.ToList());

                var latency = (int)_ingameState.CurLatency;

                foreach (var stashResults in itemsToDrop)
                {
                    // If we are more than 2 tabs away from our target, then use dropdown approach if
                    // user has it.
                    if (!Keyboard.IsKeyToggled(Settings.DropHotkey.Value))
                    {
                        return;
                    }

                    if (!SwitchToTab(stashResults.Value[0].StashNode))
                    {
                        continue;
                    }
                    try
                    {
                        Keyboard.KeyDown(Keys.LControlKey);
                        Thread.Sleep(INPUT_DELAY);

                        foreach (var stashResult in stashResults.Value)
                        {
                            Mouse.SetCursorPosAndLeftClick(stashResult.ClickPos, Settings.ExtraDelay, _windowOffset);
                            Thread.Sleep(latency + Settings.ExtraDelay.Value);
                        }
                    }
                    catch
                    {
                        Keyboard.KeyUp(Keys.LControlKey);
                    }

                    // QVIN's version of Hud doesn't support Subscription events, so we use reflection.
                    if (_callPluginEventMethod != null)
                    {
                        _callPluginEventMethod.Invoke(API, new object[] { "StashUpdate", new object[0] });
                    }
                }

                Keyboard.KeyUp(Keys.LControlKey);
            }

            ProcessRefills();
            Mouse.SetCursorPos(cursorPosPreMoving.X, cursorPosPreMoving.Y);

            // TODO:Go back to a specific tab, if user has that setting enabled.
            if (Settings.VisitTabWhenDone.Value)
            {
                SwitchToTab(Settings.TabToVisitWhenDone);
            }

            if (Settings.BlockInput.Value)
            {
                WinApi.BlockInput(false);
                Thread.Sleep(INPUT_DELAY);
            }
        }
示例#34
0
 /// <summary>
 /// Handles the EXCEPTION_STACK_OVERFLOW debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnStackOverflowDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#35
0
 /// <summary>
 /// Handles the EXCEPTION_INVALID_DISPOSITION debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnInvalidDispositionDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#36
0
        /// <summary>
        /// Handles the EXCEPTION_SINGLE_STEP debug exception.
        /// Logs information about the thread state when the exception is hit.
        /// </summary>
        /// <param name="de">The debug exception that was caught by the debugger.</param>
        /// <returns>Returns the continue debugging status code.</returns>
        protected override WinApi.DbgCode OnSingleStepDebugException(ref WinApi.DEBUG_EVENT de)
        {
            IntPtr threadHandle;
            WinApi.CONTEXT cx;
            this.BeginEditThread(de.dwThreadId, out threadHandle, out cx);
            if (this.LogRegistersOnBreakpoint)
            {
                this.LogRegisters(ref cx);
            }

            uint prevInstSize = this.GetPreviousInstructionSize(new IntPtr((long)cx._ip));
            IntPtr prevInstruction = new IntPtr((long)cx._ip - prevInstSize);
            if (this.LogBreakpointAccesses)
            {
                this.Status.Log(
                    "Modifying address is " +
                    this.IntPtrToFormattedAddress(prevInstruction) +
                    " with instruction length " + prevInstSize);
            }

            if (this.RestoreBreakpointOnExceptionSingleStep == true)
            {
                // TODO: eventually replace breakpointAddressJustHit with a check of Dr6.
                if (this.BreakpointAddressJustHit != IntPtr.Zero)
                {
                    this.Write(this.BreakpointAddressJustHit, (byte)0xcc, WriteOptions.None);
                    this.Status.Log(
                        "Restoring breakpoint at " +
                        this.IntPtrToFormattedAddress(this.BreakpointAddressJustHit));
                    this.BreakpointAddressJustHit = IntPtr.Zero;
                }
                else
                {
                    this.Status.Log(
                        "Unexpected series of events during breakpoint restoration.",
                        Logger.Logger.Level.HIGH);
                }

                this.RestoreBreakpointOnExceptionSingleStep = false;
            }

            return base.OnSingleStepDebugException(ref de);
        }
        public GatewayService(StatelessServiceContext context)
            : base(context)
        {
            WinApi.TimeBeginPeriod(1); //improve sleep precision for polling type transports

            float timeoutDebugMultiplier = 1;
            var   builder = new ContainerBuilder();

            var esLogsConfig    = new FabricConfigProvider <ElasticSearchOutputConfig>("ElasticSearchLogs").Config;
            var esMetricsConfig = new FabricConfigProvider <ElasticSearchOutputConfig>("ElasticSearchMetrics").Config;

            var logger = new LoggerConfiguration()
                         .ConfigureMOUSETypesDestructure()
                         .MinimumLevel.Error()
                         .Enrich.With(new AzureServiceFabricSerilogEnricher(context))
                         .Enrich.With <ExceptionEnricher>()
                         .Enrich.With <ActivityIdSerilogEnricher>()
                         .WriteTo.Elasticsearch(
                new ElasticsearchSinkOptions(new Uri(esLogsConfig.ElasticSearchUri))
            {
                IndexFormat = $"{esLogsConfig.ElasticSearchIndexName}-{{0:yyyy.MM.dd}}"
            })
                         .CreateLogger();

            Log.Logger = logger;

            builder.RegisterInstance(logger).As <ILogger>();
            builder.RegisterType <SerilogCoreEvents>().As <ICoreEvents>();
            builder.RegisterType <SerilogActorCoreEvents>().As <IActorCoreEvents>();
            builder.RegisterType <SerilogLidgrenEvents>().As <ILidgrenEvents>();

            Metric.Config.WithAllCounters();

            _metricsSubscription = new TelemetryPipe()
                                   .CollectMetricsNet(5, ServiceFabricHelpers.GetEnvironmentProperties(context), true)
                                   .SendToElasticSearch(esMetricsConfig)
                                   .Start();

            builder.Register(
                c => new ProtobufMessageSerializer(typeof(Message).Assembly, typeof(TestStateless).Assembly))
            .As <IMessageSerializer>();

            var publicEndpoint  = FabricRuntime.GetActivationContext().GetEndpoint("Public");
            var public2Endpoint = FabricRuntime.GetActivationContext().GetEndpoint("Public2");
            var public3Endpoint = FabricRuntime.GetActivationContext().GetEndpoint("Public3");
            var nodeIP          = Dns.GetHostAddresses(FabricRuntime.GetNodeContext().IPAddressOrFQDN).First(x => x.AddressFamily == AddressFamily.InterNetwork);

            var publicNetConfig = new NetPeerConfiguration("PublicNet")
            {
                LocalAddress              = nodeIP,
                MaximumConnections        = 10000,
                AcceptIncomingConnections = true,
                Port = publicEndpoint.Port,
                ConnectionTimeout = 10 * timeoutDebugMultiplier
            };
            var public2NetConfig = new NetPeerConfiguration("PublicNet")
            {
                LocalAddress              = nodeIP,
                MaximumConnections        = 10000,
                AcceptIncomingConnections = true,
                Port = public2Endpoint.Port,
                ConnectionTimeout = 10 * timeoutDebugMultiplier
            };

            var public3NetConfig = new NetPeerConfiguration("PublicNet")
            {
                LocalAddress              = nodeIP,
                MaximumConnections        = 10000,
                AcceptIncomingConnections = true,
                Port = public3Endpoint.Port,
                ConnectionTimeout = 10 * timeoutDebugMultiplier
            };

            var testActorsNetConfig = new NetPeerConfiguration("TestActors")
            {
                LocalAddress = nodeIP,
                AcceptIncomingConnections = false,
                Port = 0,
                ConnectionTimeout = 10 * timeoutDebugMultiplier
            };

            builder.RegisterType <WcfBufferPool>().As <IBufferPool>();

            builder.Register(c =>
            {
                var messageSerialer = c.Resolve <IMessageSerializer>();
                var coreLogger      = c.Resolve <ICoreEvents>();
                var nedNodeConfig   = c.Resolve <INetNodeConfig>();
                var bufferPool      = c.Resolve <IBufferPool>();

                return(new NetNode <SFActorsBackendClientNetChannel>("PublicNet",
                                                                     new LidgrenNetProvider(publicNetConfig, c.Resolve <ILidgrenEvents>()),
                                                                     coreLogger, messageSerialer,
                                                                     (node, transport) => new SFActorsBackendClientNetChannel(node, transport, messageSerialer, coreLogger, nedNodeConfig, bufferPool),
                                                                     nedNodeConfig));
            })
            .As <INetNode>()
            .SingleInstance();

            builder.Register(c =>
            {
                var actorSystem     = c.Resolve <IActorSystem <ITestActor> >();
                var messageSerialer = c.Resolve <IMessageSerializer>();
                var coreLogger      = c.Resolve <ICoreEvents>();
                var netNodeConfig   = c.Resolve <INetNodeConfig>();
                var bufferPool      = c.Resolve <IBufferPool>();

                return(new NetNode <MouseActorsBackendClientNetChannel>("PublicNet2",
                                                                        new LidgrenNetProvider(public2NetConfig, c.Resolve <ILidgrenEvents>()),
                                                                        coreLogger, messageSerialer,
                                                                        (node, transport) => new MouseActorsBackendClientNetChannel(actorSystem, node, transport, messageSerialer, coreLogger, netNodeConfig, bufferPool),
                                                                        netNodeConfig));
            })
            .As <INetNode>()
            .SingleInstance();

            builder.Register(c =>
            {
                var messageSerialer = c.Resolve <IMessageSerializer>();
                var coreLogger      = c.Resolve <ICoreEvents>();
                var netNodeConfig   = c.Resolve <INetNodeConfig>();
                var bufferPool      = c.Resolve <IBufferPool>();

                return(new NetNode <OrleansBackendClientNetChannel>("PublicNet3",
                                                                    new LidgrenNetProvider(public3NetConfig, c.Resolve <ILidgrenEvents>()),
                                                                    coreLogger, messageSerialer,
                                                                    (node, transport) => new OrleansBackendClientNetChannel(node, transport, messageSerialer, coreLogger, netNodeConfig, bufferPool),
                                                                    netNodeConfig));
            })
            .As <INetNode>()
            .SingleInstance();

            builder.Register(c =>
                             new ServiceFabricActorSystemNetNode <ITestActor>("TestActors", new Uri("fabric:/MouseTestActor.Deploy/MouseTestActor"),
                                                                              new LidgrenNetProvider(testActorsNetConfig, c.Resolve <ILidgrenEvents>()),
                                                                              c.Resolve <IActorCoreEvents>(), c.Resolve <ICoreEvents>(), c.Resolve <IMessageSerializer>(), c.Resolve <INetNodeConfig>(), c.Resolve <IBufferPool>()))
            .As <INetNode>()
            .As <IActorSystem <ITestActor> >()
            .SingleInstance();

            builder.Register(c => new NetNodeConfig()
            {
                SendTimeoutSec    = (int)(10.0 * timeoutDebugMultiplier),
                ConnectTimeoutSec = (int)(10 * timeoutDebugMultiplier)
            }).As <INetNodeConfig>();

            var container = builder.Build();

            _netNodes = container.Resolve <IEnumerable <INetNode> >();

            var config = new ClientConfiguration
            {
                //DataConnectionString = "DefaultEndpointsProtocol=https;AccountName=actorchatstorage;AccountKey=1hCY/Ak2TFrqE61cMhbPU5rkv9PuDfX7QQFU4tXCSc2AO78hLdm6u3PrGrZbUzOj7OkIZ93YKbU81VSVnBMbPg==",
                DataConnectionString       = "UseDevelopmentStorage=true",
                PropagateActivityId        = true,
                DefaultTraceLevel          = Severity.Info,
                GatewayProvider            = ClientConfiguration.GatewayProviderType.AzureTable,
                TraceToConsole             = true,
                StatisticsCollectionLevel  = StatisticsLevel.Critical,
                StatisticsLogWriteInterval = TimeSpan.FromDays(6),
                TraceFileName    = null,
                TraceFilePattern = null,
                ResponseTimeout  = TimeSpan.FromSeconds(90),
                StatisticsMetricsTableWriteInterval = TimeSpan.FromDays(6),
                StatisticsPerfCountersWriteInterval = TimeSpan.FromDays(6),
            };

            OrleansFabricClient.Initialize(new Uri("fabric:/OrleansTest/OrleansTestActor"), config);
        }
示例#38
0
 private static extern int SetWinEventHook(int eventMin, int eventMax, IntPtr hmodWinEventProc, WinApi.WinEventHookProc lpfnWinEventProc, int idProcess, int idThread, int dwflags);
示例#39
0
 /// <summary>
 /// Returns true if the cursor is within the form window
 /// </summary>
 public static bool IsMouseIn()
 {
     return(WinApi.IsCursorIn(_form.Handle));
 }
示例#40
0
        //  Sends input (keyboard/mouse) to screen which has focus (top-most)
        public void HandleInput()
        {
            ProfilerShort.Begin("MyGuiManager.HandleInput");
            try
            {
                if (MyInput.Static.IsAnyAltKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.F4))
                {
                    MyAnalyticsTracker.SendGameEnd("Alt+F4", MySandboxGame.TotalTimeInMilliseconds / 1000);

                    //  Exit application
                    MySandboxGame.ExitThreadSafe();
                    return;
                }

                //  Screenshot(s)
                if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.SCREENSHOT))
                {
                    MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick);
                    TakeScreenshot();
                }

                bool newPressf12 = MyInput.Static.IsNewKeyPressed(MyKeys.F12);
                bool newPressf2  = MyInput.Static.IsNewKeyPressed(MyKeys.F2);
                if ((newPressf2 || newPressf12) && MyInput.Static.IsAnyShiftKeyPressed() && MyInput.Static.IsAnyAltKeyPressed())
                {
                    if (MySession.Static != null && MySession.Static.CreativeMode)
                    {
                        if (newPressf12)
                        {
                            MyDebugDrawSettings.DEBUG_DRAW_PHYSICS = !MyDebugDrawSettings.DEBUG_DRAW_PHYSICS;
                            if (!m_shapeRenderingMessageBoxShown)
                            {
                                m_shapeRenderingMessageBoxShown = true;
                                AddScreen(MyGuiSandbox.CreateMessageBox(
                                              messageCaption: new StringBuilder("PHYSICS SHAPES"),
                                              messageText: new StringBuilder("Enabled physics shapes rendering. This feature is for modders only and is not part of the gameplay.")));
                            }
                        }
                    }
                    else
                    {
                        AddScreen(MyGuiSandbox.CreateMessageBox(
                                      messageCaption: new StringBuilder("MODDING HELPER KEYS"),
                                      messageText: new StringBuilder("Use of helper key combinations for modders is only allowed in creative mode.")));
                    }
                    return;
                }

                if (MyInput.Static.IsNewKeyPressed(MyKeys.H) && MyInput.Static.IsAnyCtrlKeyPressed())
                {
                    if (MyFakes.ENABLE_NETGRAPH)
                    {
                        MyHud.IsNetgraphVisible = !MyHud.IsNetgraphVisible;
                    }
                }

                if (MyInput.Static.IsNewKeyPressed(MyKeys.F11))
                {
                    if (MyInput.Static.IsAnyShiftKeyPressed() && !MyInput.Static.IsAnyCtrlKeyPressed())
                    {
                        SwitchTimingScreen();
                    }
                }

                if (MyFakes.ENABLE_MISSION_SCREEN && MyInput.Static.IsNewKeyPressed(MyKeys.U))
                {
                    MyScreenManager.AddScreen(new MyGuiScreenMission());
                }

                if (!MyInput.Static.ENABLE_DEVELOPER_KEYS && Sync.MultiplayerActive && m_currentDebugScreen is MyGuiScreenDebugOfficial)
                {
                    RemoveScreen(m_currentDebugScreen);
                    m_currentDebugScreen = null;
                }

                bool inputHandled = false;

                if (MySession.Static != null && MySession.Static.CreativeMode ||
                    MyInput.Static.ENABLE_DEVELOPER_KEYS)
                {
                    F12Handling();
                }

                if (MyInput.Static.ENABLE_DEVELOPER_KEYS)
                {
                    //  Statistics screen
                    if (MyInput.Static.IsNewKeyPressed(MyKeys.F11) && !MyInput.Static.IsAnyShiftKeyPressed() && MyInput.Static.IsAnyCtrlKeyPressed())
                    {
                        SwitchStatisticsScreen();
                    }

                    if (MyInput.Static.IsAnyShiftKeyPressed() && MyInput.Static.IsAnyAltKeyPressed() && MyInput.Static.IsAnyCtrlKeyPressed() &&
                        MyInput.Static.IsNewKeyPressed(MyKeys.Home))
                    {
                        throw new InvalidOperationException("Controlled crash");
                    }

                    // Forge GC to run
                    if (MyInput.Static.IsNewKeyPressed(MyKeys.Pause) && MyInput.Static.IsAnyShiftKeyPressed())
                    {
                        GC.Collect(GC.MaxGeneration);
                    }

                    if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.F2))
                    {
                        //Reload textures
                        if (MyInput.Static.IsKeyPress(MyKeys.LeftShift))
                        {
                            MyDefinitionManager.Static.ReloadDecalMaterials();
                            VRageRender.MyRenderProxy.ReloadTextures();
                        }
                        else
                        if (MyInput.Static.IsKeyPress(MyKeys.LeftAlt))
                        {
                            VRageRender.MyRenderProxy.ReloadModels();
                        }
                        else
                        {
                            VRageRender.MyRenderProxy.ReloadEffects();
                        }
                    }

                    //WS size
                    if (MyInput.Static.IsNewKeyPressed(MyKeys.F3) && MyInput.Static.IsKeyPress(MyKeys.LeftShift))
                    {
#if !XB1
                        WinApi.SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
#endif // !XB1
                    }

                    inputHandled = HandleDebugInput();
                }

                if (!inputHandled)
                {
                    MyScreenManager.HandleInput();
                }
            }
            finally
            {
                ProfilerShort.End();
            }
        }
示例#41
-1
        public void DetachDialog(WinApi.Button btn)
        {
            try
            {
                btn.ClickAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生异常,请截图并发至ydwe论坛:" + Environment.NewLine
                    + "原文本框句柄:" + hEdit.ToString() + Environment.NewLine
                    + "确认按钮句柄:" + hBtnOk.ToString() + Environment.NewLine
                    + "取消按钮句柄:" + hBtnCancel.ToString() + Environment.NewLine
                    + "异常信息:" + ex.ToString());
            }

            Config.SaveColor(btn1stColor);
            Config.SaveColor(btn2ndColor);
            Config.SaveColor(btn3rdColor);
            Config.SaveColor(btn4thColor);

            Config.SaveDialogSize(this);

            this.txtEdit.undoStack.Clear();// 清空撤销信息
            this.btnUndo.Enabled = false;
            this.txtEdit.redoStack.Clear();// 清空重做信息
            this.btnRedo.Enabled = false;

            this.Hide();// 隐藏模拟窗口
            //this.Dispose();// 销毁模拟窗口
            this.hWnd = IntPtr.Zero;
        }
示例#42
-1
 public void WinApi_ListWinData_Test()
 {
     var api = new WinApi();
     foreach(var win in api.GetWindows(true))
     {
         Console.WriteLine(win);
     }
 }
示例#43
-1
        /// <summary>
        /// Initializes a new instance of the Region class.
        /// </summary>
        /// <param name="baseAddress">The base address of the region.</param>
        /// <param name="size">The size of the region.</param>
        /// <param name="protection">The protection settings on this region.</param>
        /// <param name="type">The type of the memory region.</param>
        public Region(IntPtr baseAddress, uint size, WinApi.MemoryProtect protection, WinApi.MemoryType type)
        {
            this.Size = size;
            this.BaseAddress = new Address(baseAddress, this.Size);
            this.matches = new bool[this.Size];
            this.Protect = protection;
            this.Type = type;

            // might want to import and use memset, if this for loop is really slow
            for (uint i = 0; i < this.Size; ++i)
            {
                this.matches[i] = true;
            }
        }
示例#44
-1
文件: Devices.cs 项目: SayHalou/ospy
 private Device (IntPtr devInfo, WinApi.SP_DEVINFO_DATA devInfoData, string name, string hardwareId, string physicalDeviceObjectName, UInt32 capabilities)
 {
     this.devInfo = devInfo;
     this.devInfoData = devInfoData;
     this.name = name;
     this.hardwareId = hardwareId;
     this.physicalDeviceObjectName = physicalDeviceObjectName;
     this.capabilities = capabilities;
 }
示例#45
-1
文件: Devices.cs 项目: SayHalou/ospy
        public static Device FromDevInfo (IntPtr devInfo, WinApi.SP_DEVINFO_DATA devInfoData)
        {
            Device device = null;

            string name = null;
            string hardwareId = null;
            string physicalDeviceObjectName = null;
            UInt32 capabilities = 0;

            byte[] buf = new byte[1024];
            uint reqBufSize;

            if (WinApi.SetupDiGetDeviceRegistryProperty (devInfo, ref devInfoData, WinApi.SPDRP_FRIENDLYNAME, IntPtr.Zero, buf, (uint) buf.Length, out reqBufSize))
            {
                name = WinApi.ByteArrayToString (buf);
            }

            if (name == null)
            {
                if (WinApi.SetupDiGetDeviceRegistryProperty (devInfo, ref devInfoData, WinApi.SPDRP_DEVICEDESC, IntPtr.Zero, buf, (uint)buf.Length, out reqBufSize))
                {
                    name = WinApi.ByteArrayToString (buf);
                }
            }

            if (WinApi.SetupDiGetDeviceRegistryProperty (devInfo, ref devInfoData, WinApi.SPDRP_HARDWAREID, IntPtr.Zero, buf, (uint)buf.Length, out reqBufSize))
            {
                string[] tokens = WinApi.MarshalMultiStringToStringArray (buf);
                hardwareId = String.Join (";", tokens);
            }

            if (WinApi.SetupDiGetDeviceRegistryProperty (devInfo, ref devInfoData, WinApi.SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, IntPtr.Zero, buf, (uint)buf.Length, out reqBufSize))
            {
                physicalDeviceObjectName = WinApi.ByteArrayToString (buf);
            }

            if (WinApi.SetupDiGetDeviceRegistryProperty (devInfo, ref devInfoData, WinApi.SPDRP_CAPABILITIES, IntPtr.Zero, buf, (uint)buf.Length, out reqBufSize))
            {
                capabilities = BitConverter.ToUInt32 (buf, 0);
            }

            if (name != null && hardwareId != null)
            {
                device = new Device (devInfo, devInfoData, name, hardwareId, physicalDeviceObjectName, capabilities);
            }

            return device;
        }
示例#46
-1
 /// <summary>
 /// Handles the OUTPUT_DEBUG_STRING_EVENT debug event.
 /// </summary>
 /// <param name="de">The debug event that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnOutputDebugStringEvent(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.CONTINUE;
 }
示例#47
-1
        /// <summary>
        /// Apply the thread context modification and resume the thread.
        /// </summary>
        /// <param name="threadId">The ID of the thread to be modified.</param>
        /// <param name="threadHandle">A handle of the thread to be modified.</param>
        /// <param name="cx">The context of the thread to be modified.</param>
        protected void EndEditThread(uint threadId, ref IntPtr threadHandle, ref WinApi.CONTEXT cx)
        {
            // TODO: get the most context data from the thread, if FULL cannot get the most.
            cx.ContextFlags = WinApi.CONTEXT_FLAGS.FULL;
            if (!WinApi.SetThreadContext(threadHandle, ref cx))
            {
                string msg =
                    "Unable to set thread context for TID: " + threadId + ". Error: " +
                    Marshal.GetLastWin32Error();
                WinApi.CloseHandle(threadHandle);
                throw new InvalidOperationException(msg);
            }

            uint res = WinApi.ResumeThread(threadHandle);
            unchecked
            {
                if (res == (uint)(-1))
                {
                    string msg =
                        "Unable to resume thread, TID: " + threadId + ". Error: " + Marshal.GetLastWin32Error();
                    WinApi.CloseHandle(threadHandle);
                    throw new InvalidOperationException(msg);
                }
            }
        }
示例#48
-1
 /// <summary>
 /// Handles the CREATE_THREAD_DEBUG_EVENT debug event.
 /// </summary>
 /// <param name="de">The debug event that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnCreateThreadDebugEvent(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.CONTINUE;
 }
示例#49
-1
 /// <summary>
 /// Handles the EXIT_PROCESS_DEBUG_EVENT debug event.
 /// </summary>
 /// <param name="de">The debug event that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnExitProcessDebugEvent(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.CONTINUE;
 }
示例#50
-1
 /// <summary>
 /// Handles the UNLOAD_DLL_DEBUG_EVENT debug event.
 /// </summary>
 /// <param name="de">The debug event that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnUnloadDllDebugEvent(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.CONTINUE;
 }
示例#51
-1
        /// <summary>
        /// Handles the EXCEPTION_BREAKPOINT debug exception.
        /// Causes the process to trigger a single step debug exception.
        /// </summary>
        /// <param name="de">The debug exception that was caught by the debugger.</param>
        /// <returns>Returns the continue debugging status code.</returns>
        protected override WinApi.DbgCode OnBreakpointDebugException(ref WinApi.DEBUG_EVENT de)
        {
            if (this.InitialBreakpointHit)
            {
                this.Restore(de.Exception.ExceptionRecord.ExceptionAddress, false);
                //this.SetIP(de.Exception.ExceptionRecord.ExceptionAddress);
                //this.PrepareForSingleStep(de.Exception.ExceptionRecord.ExceptionAddress);
                this.BreakpointAddressJustHit = de.Exception.ExceptionRecord.ExceptionAddress;
                this.RestoreBreakpointOnExceptionSingleStep = true;
            }

            return base.OnBreakpointDebugException(ref de);
        }
示例#52
-1
 /// <summary>
 /// Handles the EXCEPTION_FLT_DENORMAL_OPERAND debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnFltDenormalOperandDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#53
-1
 /// <summary>
 /// Handles the EXCEPTION_FLT_INEXACT_RESULT debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnFltInexactResultDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#54
-1
 /// <summary>
 /// Handles the EXCEPTION_SINGLE_STEP debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnSingleStepDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#55
-1
 /// <summary>
 /// Handles the EXCEPTION_IN_PAGE_ERROR debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnInPageErrorDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#56
-1
 /// <summary>
 /// Handles the EXCEPTION_NONCONTINUABLE_EXCEPTION debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnNoncontinuableExceptionDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#57
-1
        /// <summary>
        /// Suspend the thread and prepare the thread context to be modified.
        /// </summary>
        /// <param name="threadId">The ID of the thread to be modified.</param>
        /// <param name="threadHandle">A handle of the thread to be modified.</param>
        /// <param name="cx">The context of the thread to be modified.</param>
        protected void BeginEditThread(uint threadId, out IntPtr threadHandle, out WinApi.CONTEXT cx)
        {
            WinApi.ThreadAccess threadRights =
                WinApi.ThreadAccess.SET_CONTEXT |
                WinApi.ThreadAccess.GET_CONTEXT |
                WinApi.ThreadAccess.SUSPEND_RESUME;
            threadHandle = WinApi.OpenThread(threadRights, false, threadId);
            if (threadHandle == null || threadHandle.Equals(IntPtr.Zero))
            {
                string msg =
                    "Unable to obtain a thread handle for TID: " + threadId + ". Error: " +
                    Marshal.GetLastWin32Error();
                WinApi.CloseHandle(threadHandle);
                throw new InvalidOperationException(msg);
            }

            uint result = WinApi.SuspendThread(threadHandle);
            unchecked
            {
                if (result == (uint)(-1))
                {
                    string msg =
                        "Unable to suspend thread, TID: " + threadId + ". Error: " + Marshal.GetLastWin32Error();
                    WinApi.CloseHandle(threadHandle);
                    throw new InvalidOperationException(msg);
                }
            }

            WinApi.CONTEXT context = new WinApi.CONTEXT();
            context.ContextFlags = WinApi.CONTEXT_FLAGS.FULL;
            if (!WinApi.GetThreadContext(threadHandle, ref context))
            {
                string msg =
                    "Unable to get thread context, TID: " + threadId + ". Error: " + Marshal.GetLastWin32Error();
                WinApi.CloseHandle(threadHandle);
                throw new InvalidOperationException(msg);
            }

            cx = context;
        }
示例#58
-1
 /// <summary>
 /// Handles the EXCEPTION_INT_DIVIDE_BY_ZERO debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnIntDivideByZeroDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#59
-1
 /// <summary>
 /// Handles the default case where no debug exception can handle this debug event.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnUnhandledDebugException(ref WinApi.DEBUG_EVENT de)
 {
     this.Status.Log(
         "An unhandled (default) debug exception occurred. " +
         "Exception code: 0x" + de.Exception.ExceptionRecord.ExceptionCode.ToString("x"),
         Logger.Level.DEBUG);
     return WinApi.DbgCode.EXCEPTION_NOT_HANDLED;
 }
示例#60
-1
 /// <summary>
 /// Handles the EXCEPTION_GUARD_PAGE debug exception.
 /// </summary>
 /// <param name="de">The debug exception that was caught by the debugger.</param>
 /// <returns>Returns the continue debugging status code.</returns>
 protected virtual WinApi.DbgCode OnGuardPageDebugException(ref WinApi.DEBUG_EVENT de)
 {
     return WinApi.DbgCode.CONTINUE;
 }