コード例 #1
0
        public Screenshot(IntPtr targetWindow, ScreenshotMethod method, bool withSolidGlass)
        {
            this.TargetHandle = targetWindow == IntPtr.Zero ? Windowing.GetForegroundWindow() : targetWindow;
            this.WindowClass  = Windowing.GetWindowClass(TargetHandle);

            Trace.WriteLine(string.Format("Requested method is '{0}'", method), string.Format("Screenshot.ctor [{0}]", System.Threading.Thread.CurrentThread.Name));

            this.Method = method == ScreenshotMethod.Auto ? ScreenshotMethod.DWM : method;
            this.Method = FMUtils.WinApi.Helper.VisualStyle != Helper.VisualStyles.Aero ? ScreenshotMethod.GDI : this.Method;

            //I cannot recall why I uncommented the above and used this instead, undoing until I remember
            //this.Method = method;

            Trace.WriteLine(string.Format("Actual method is '{0}'", this.Method), string.Format("Screenshot.ctor [{0}]", System.Threading.Thread.CurrentThread.Name));

            //this.TargetRect = isMaximized ? Screen.FromHandle(TargetHandle).WorkingArea : Helper.GetWindowRectangle(TargetHandle);
            this.TargetRect   = Helper.GetWindowRectangleDPI(TargetHandle);
            this.isMaximized  = Helper.IsWindowMazimized(TargetHandle);
            this.TargetScreen = Screen.FromHandle(TargetHandle);

            this.BaseScreenshotImage = this.Method == ScreenshotMethod.DWM ? ScreenshotWindowDWM(TargetHandle, withSolidGlass) : ScreenshotWindowGDI(TargetHandle, withSolidGlass);

            this.isRounded = !Helper.IsSquareWindowEdge(TargetHandle);

            this.WindowTitle = WinApi.Helper.GetWindowText(TargetHandle, true);
            this.Date        = DateTime.Now;
        }
コード例 #2
0
        public NoiseVocoder(
            IBGCStream stream,
            double freqLowerBound            = 20.0,
            double freqUpperBound            = 16000.0,
            int bandCount                    = 22,
            int fftSize                      = 4096,
            int overlapRatio                 = 4,
            TransformRMSBehavior rmsBehavior = TransformRMSBehavior.Passthrough,
            Random randomizer                = null)
            : base(stream)
        {
            if (stream.Channels != 1)
            {
                throw new StreamCompositionException(
                          $"Noise Vocoder requires a mono input stream. Input stream has {stream.Channels} channels.");
            }

            this.fftSize      = fftSize;
            this.overlapRatio = overlapRatio;
            stepSize          = fftSize / overlapRatio;
            overlapSize       = fftSize - stepSize;

            inputBuffer        = new float[fftSize];
            noiseBuffer        = new double[fftSize];
            outputAccumulation = new double[fftSize];
            cachedSampleBuffer = new float[stepSize];

            noiseFFTBuffer  = new Complex64[fftSize];
            signalFFTBuffer = new Complex64[fftSize];

            amplitudeBuffers = new Complex64[bandCount][];
            noiseBandBuffers = new Complex64[bandCount][];

            for (int i = 0; i < bandCount; i++)
            {
                amplitudeBuffers[i] = new Complex64[fftSize];
                noiseBandBuffers[i] = new Complex64[fftSize];
            }

            initialized = false;

            noiseScalarA = Math.Sqrt(1.0 / 3.0);
            noiseScalarB = 2.0 * noiseScalarA;

            double[] windowTemplate = Windowing.GetHalfWindow64(Windowing.Function.BlackmanHarris, fftSize / 2);

            window = new double[fftSize];
            for (int i = 0; i < fftSize / 2; i++)
            {
                window[i] = windowTemplate[i];
                window[fftSize - i - 1] = windowTemplate[i];
            }

            this.randomizer  = randomizer ?? new Random(CustomRandom.Next());
            this.rmsBehavior = rmsBehavior;

            bandFrequencies = GetExponentialDistribution(freqLowerBound, freqUpperBound, bandCount).ToArray();

            outputFactor = 0.5 * Math.Sqrt(fftSize) / overlapRatio;
        }
コード例 #3
0
ファイル: Engine.cs プロジェクト: johang88/triton
        public Engine(Windowing.IWindowProvider windowProvider, SharpFileSystem.IFileSystem fileSystem)
        {
            WindowProvider = windowProvider;

            // Initialize file system and resource manager
            FileSystem = new Common.IO.FileSystem(fileSystem);

            ResourceGroupManager = new Common.ResourceGroupManager(FileSystem);
            CoreResources = ResourceGroupManager.Add("core", 100);
            GameResources = ResourceGroupManager.Add("game", 10);

            // Setup graphics core
            GraphicsBackend = new Graphics.Backend(CoreResources, WindowProvider.Width, WindowProvider.Height, WindowProvider.WindowInfo);

            // Init resource loaders
            RegisterResourceLoaders(CoreResources);
            RegisterResourceLoaders(GameResources);

            // High level renderer (deferred + hdr)
            Renderer = new RendererImplementation(FileSystem, CoreResources, GraphicsBackend);

            // The input stuff
            InputManager = new Input.InputManager(WindowProvider.Bounds);

            // Setup game world
            GameWorld = new GameWorld(GameResources, GraphicsBackend);
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: jzabroski/ProSnap
        private static void Main()
        {
            Trace.Listeners.Add(new ReportListener());

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;

            //todo: It's reccomended that this be set in the manifest, but I can't figure out how to do that successfully with clickonce
            Windowing.SetProcessDPIAware();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            System.Threading.Thread.CurrentThread.Name = "Main UI " + System.Threading.Thread.CurrentThread.ManagedThreadId;
            Update.CheckForUpdate();

            History = new List <ExtendedScreenshot>();

            Preview  = new PeekPreview();
            Selector = new RegionSelector();
            Trace.WriteLine(string.Format("Forcing the creation of windows by accessing their handles on the Main UI thread: {0}, {1}", Preview.Handle, Selector.Handle), string.Format("Program [{0}]", System.Threading.Thread.CurrentThread.Name));

            KeyboardHook = new Hook("Global Action Hook");
            KeyboardHook.KeyDownEvent += KeyDown;
            KeyboardHook.KeyUpEvent   += KeyUp;

            TrayIcon = new NotifyIcon()
            {
                Icon             = ProSnap.Properties.Resources.camera_36x36_icon,
                Text             = "ProSnap",
                Visible          = true,
                ContextMenuStrip = new ContextMenuStrip()
            };

            //TrayIcon.ContextMenuStrip.Items.Add("Take Screenshot", null, new EventHandler((o, e) => { Thread.Sleep(3000); SpawnActionChain(ActiveShortcutProfile.Shortcuts.FirstOrDefault(s => s.Actions.ActionItems.FirstOrDefault().ActionType == ActionTypes.TakeForegroundScreenshot)); }));

            TrayIcon.ContextMenuStrip.Items.Add(new ToolStripMenuItem("History", null, (o, e) => (o as ToolStripMenuItem).ShowDropDown())
            {
                Name = "tsmiHistory"
            });
            TrayIcon.ContextMenuStrip.Items.Add("Options", null, (o, e) => Options.Options.ShowOrActivate());
            TrayIcon.ContextMenuStrip.Items.Add("Exit", null, (o, e) =>
            {
                Application.Exit();
                DumpTraceReport();
            });

            TrayIcon.MouseDown += TrayIcon_MouseDown;

            IconAnimation.WorkerSupportsCancellation = true;
            IconAnimation.DoWork += IconAnimation_DoWork;

            Application.Run();

            KeyboardHook.isPaused = true;
            TrayIcon.Visible      = false;
        }
コード例 #5
0
        public StreamWindower(
            IBGCStream stream,
            Windowing.Function function      = Windowing.Function.Hamming,
            double totalDuration             = double.NaN,
            int smoothingSamples             = 1000,
            int sampleShift                  = 0,
            TransformRMSBehavior rmsBehavior = TransformRMSBehavior.Passthrough)
            : base(stream)
        {
            if (sampleShift > stream.ChannelSamples)
            {
                Debug.LogError("Requested a sampleOffset larger than clip length");
                sampleShift = 0;
            }

            this.sampleShift = sampleShift;

            if (!double.IsNaN(totalDuration))
            {
                ChannelSamples = Math.Min(
                    (int)Math.Round(totalDuration * SamplingRate),
                    stream.ChannelSamples - sampleShift);
                TotalSamples = Channels * ChannelSamples;
            }
            else
            {
                if (stream.ChannelSamples == int.MaxValue)
                {
                    ChannelSamples = int.MaxValue;
                    TotalSamples   = int.MaxValue;
                }
                else
                {
                    ChannelSamples = stream.ChannelSamples - sampleShift;
                    TotalSamples   = Channels * ChannelSamples;
                }
            }

            this.rmsBehavior = rmsBehavior;

            smoothingSamples = Math.Min(smoothingSamples, ChannelSamples / 2);

            openingWindow = Windowing.GetHalfWindow(function, smoothingSamples);
            closingWindow = openingWindow;

            endOpeningWindow   = smoothingSamples;
            startClosingWindow = ChannelSamples - smoothingSamples;

            Reset();
        }
コード例 #6
0
        private void LoadDesktopThumb()
        {
            Screenshot TaskBar = new Screenshot(Windowing.FindWindow("Shell_TrayWnd", null), ScreenshotMethod.DWM, false);
            string     DesktopWallpaperPath = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop").GetValue("Wallpaper") as string;

            Bitmap CompositedDesktop = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

            using (Graphics composite = Graphics.FromImage(CompositedDesktop))
            {
                if (string.IsNullOrWhiteSpace(DesktopWallpaperPath))
                {
                    string[] BGColor = (Registry.CurrentUser.OpenSubKey(@"Control Panel\Colors").GetValue("Background", string.Empty) as string).Split(' ');
                    if (BGColor.Length >= 3)
                    {
                        int r, g, b;
                        if (int.TryParse(BGColor[0], out r) && int.TryParse(BGColor[1], out g) && int.TryParse(BGColor[2], out b))
                        {
                            composite.FillRectangle(new SolidBrush(Color.FromArgb(r, g, b)), 0, 0, CompositedDesktop.Width, CompositedDesktop.Height);
                        }
                    }
                }
                else
                {
                    Image DesktopWallpaper = Image.FromFile(DesktopWallpaperPath);
                    composite.DrawImage(DesktopWallpaper, new Rectangle(0, 0, CompositedDesktop.Width, CompositedDesktop.Height), new Rectangle(0, 0, DesktopWallpaper.Width, DesktopWallpaper.Height), GraphicsUnit.Pixel);
                }

                switch (FMUtils.WinApi.Helper.GetTaskbarEdge())
                {
                case DockStyle.Top:
                case DockStyle.Left: composite.DrawImageUnscaled(TaskBar.BaseScreenshotImage, 0, 0); break;

                case DockStyle.Bottom: composite.DrawImageUnscaled(TaskBar.BaseScreenshotImage, 0, Screen.PrimaryScreen.Bounds.Height - TaskBar.BaseScreenshotImage.Height); break;

                case DockStyle.Right: composite.DrawImageUnscaled(TaskBar.BaseScreenshotImage, Screen.PrimaryScreen.Bounds.Width - TaskBar.BaseScreenshotImage.Width, 0); break;
                }

                composite.Save();
            }

            pbDesktopPreview.Image         = CompositedDesktop;
            pnPreviewLocationChooser.Width = (int)((float)pbDesktopPreview.Height * ((float)CompositedDesktop.Width / (float)CompositedDesktop.Height)) + 1;
            pnPreviewLocationChooser.Left  = (int)((float)this.Width / 2.0 - (float)pnPreviewLocationChooser.Width / 2.0);
        }
コード例 #7
0
ファイル: RunAction.cs プロジェクト: jzabroski/ProSnap
        public ExtendedScreenshot Invoke(ExtendedScreenshot LatestScreenshot)
        {
            Trace.WriteLine("Applying RunAction...", string.Format("RunAction.Invoke [{0}]", System.Threading.Thread.CurrentThread.Name));

            if (LatestScreenshot == null)
            {
                Trace.WriteLine("Latest Screenshot is null, continuing...", string.Format("RunAction.Invoke [{0}]", System.Threading.Thread.CurrentThread.Name));
                return(null);
            }

            if (!File.Exists(LatestScreenshot.InternalFileName))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(LatestScreenshot.InternalFileName));
                LatestScreenshot.ComposedScreenshotImage.Save(LatestScreenshot.InternalFileName, ImageFormat.Png);
            }

            var parameters = Helper.ExpandParameters(this.Parameters, LatestScreenshot);
            var working    = Environment.ExpandEnvironmentVariables(Helper.ExpandParameters(this.WorkingDirectory, LatestScreenshot));

            switch (this.Mode)
            {
            case RunAction.Modes.ShellVerb:
            {
                Windowing.ShellExecute(IntPtr.Zero, this.ShellVerb, LatestScreenshot.InternalFileName, parameters, working, Windowing.ShowCommands.SW_NORMAL);
            } break;

            case RunAction.Modes.FilePath:
            {
                var psi = new ProcessStartInfo(Environment.ExpandEnvironmentVariables(Helper.ExpandParameters(this.ApplicationPath, LatestScreenshot)), parameters)
                {
                    UseShellExecute  = false,
                    WorkingDirectory = working,
                    CreateNoWindow   = this.HideCommandPrompt,
                };

                Process.Start(psi);
            } break;
            }

            return(LatestScreenshot);
        }
コード例 #8
0
ファイル: PeekPreview.cs プロジェクト: jzabroski/ProSnap
        private void OpenInEditor()
        {
            isEditing = true;

            if (!File.Exists(CurrentScreenshot.InternalFileName))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(CurrentScreenshot.InternalFileName));
                CurrentScreenshot.ComposedScreenshotImage.Save(CurrentScreenshot.InternalFileName, ImageFormat.Png);
            }

            Windowing.ShellExecute(IntPtr.Zero, "edit", CurrentScreenshot.InternalFileName, string.Empty, string.Empty, Windowing.ShowCommands.SW_NORMAL);

            var fsw = new FileSystemWatcher(Path.GetDirectoryName(CurrentScreenshot.InternalFileName), "*" + Path.GetExtension(CurrentScreenshot.InternalFileName));

            fsw.Changed += (s_fsw, e_args) => this.BeginInvoke(new Action(() => WriteCompleteCheck.Enabled = true));

            var async = new BackgroundWorker();

            async.DoWork += (o, a) => fsw.WaitForChanged(WatcherChangeTypes.Changed);
            async.RunWorkerAsync();
        }
コード例 #9
0
        public AnalyticStreamWindower(
            IAnalyticStream stream,
            Windowing.Function function,
            double totalDuration             = double.NaN,
            int smoothingSamples             = 1000,
            int sampleOffset                 = 0,
            TransformRMSBehavior rmsBehavior = TransformRMSBehavior.Passthrough)
            : base(stream)
        {
            if (sampleOffset > stream.Samples)
            {
                Debug.LogError("Requested a sampleOffset larger than clip length");
                sampleOffset = 0;
            }

            this.sampleOffset = sampleOffset;

            if (!double.IsNaN(totalDuration))
            {
                Samples = Math.Min(
                    (int)(totalDuration * SamplingRate),
                    stream.Samples - sampleOffset);
            }
            else
            {
                Samples = stream.Samples - sampleOffset;
            }

            this.rmsBehavior = rmsBehavior;

            smoothingSamples = Math.Min(smoothingSamples, Samples / 2);

            window = Windowing.GetHalfWindow64(function, smoothingSamples);

            endOpeningWindow   = smoothingSamples;
            startClosingWindow = Samples - smoothingSamples;

            Reset();
        }
コード例 #10
0
        public StreamWindower(
            IBGCStream stream,
            Windowing.Function function = Windowing.Function.Hamming,
            double totalDuration        = double.NaN,
            int smoothingSamples        = 1000,
            int sampleOffset            = 0,
            bool recalculateRMS         = false)
            : base(stream)
        {
            if (sampleOffset > stream.ChannelSamples)
            {
                Debug.LogError("Requested a sampleOffset larger than clip length");
                sampleOffset = 0;
            }

            this.sampleOffset = sampleOffset;

            if (!double.IsNaN(totalDuration))
            {
                ChannelSamples = Math.Min(
                    (int)(totalDuration * SamplingRate),
                    stream.ChannelSamples - sampleOffset);
            }
            else
            {
                ChannelSamples = stream.ChannelSamples - sampleOffset;
            }

            this.recalculateRMS = recalculateRMS;

            smoothingSamples = Math.Min(smoothingSamples, ChannelSamples / 2);

            window = Windowing.GetHalfWindow(function, smoothingSamples);

            endOpeningWindow   = smoothingSamples;
            startClosingWindow = ChannelSamples - smoothingSamples;

            Reset();
        }
コード例 #11
0
        public StreamWindower(
            IBGCStream stream,
            Windowing.Function openingFunction,
            Windowing.Function closingFunction,
            int openingSmoothingSamples      = 1000,
            int closingSmoothingSamples      = 1000,
            int sampleShift                  = 0,
            int totalChannelSamples          = -1,
            TransformRMSBehavior rmsBehavior = TransformRMSBehavior.Passthrough)
            : base(stream)
        {
            if (sampleShift > stream.ChannelSamples)
            {
                Debug.LogError("Requested a sampleOffset larger than clip length");
                sampleShift = 0;
            }

            this.sampleShift = sampleShift;
            this.rmsBehavior = rmsBehavior;

            if (totalChannelSamples != -1)
            {
                ChannelSamples = Math.Min(
                    totalChannelSamples,
                    stream.ChannelSamples - sampleShift);
                TotalSamples = Channels * ChannelSamples;
            }
            else
            {
                if (stream.ChannelSamples == int.MaxValue)
                {
                    ChannelSamples = int.MaxValue;
                    TotalSamples   = int.MaxValue;
                }
                else
                {
                    ChannelSamples = stream.ChannelSamples - sampleShift;
                    TotalSamples   = Channels * ChannelSamples;
                }
            }

            if (openingSmoothingSamples + closingSmoothingSamples > ChannelSamples)
            {
                //Requested smoothing samples exceeded remaining stream length
                int totalSmoothingSamples = openingSmoothingSamples + closingSmoothingSamples;
                int excessSamples         = ChannelSamples - totalSmoothingSamples;

                //Allocate reduced smoothing samples based on requested percentage
                openingSmoothingSamples -= (int)Math.Round(
                    excessSamples * (openingSmoothingSamples / (double)totalSmoothingSamples));
                closingSmoothingSamples = ChannelSamples - openingSmoothingSamples;
            }

            openingWindow = Windowing.GetHalfWindow(openingFunction, openingSmoothingSamples);
            closingWindow = Windowing.GetHalfWindow(closingFunction, closingSmoothingSamples);

            endOpeningWindow   = openingSmoothingSamples;
            startClosingWindow = ChannelSamples - closingSmoothingSamples;

            Reset();
        }
コード例 #12
0
        //cf. http://stackoverflow.com/a/1020819/1569
        internal static Bitmap GetCursor()
        {
            Windowing.CURSORINFO cursorInfo = new Windowing.CURSORINFO();
            cursorInfo.cbSize = Marshal.SizeOf(cursorInfo);
            if (!Windowing.GetCursorInfo(out cursorInfo))
            {
                return(null);
            }

            if (cursorInfo.flags != Windowing.CURSOR_SHOWING)
            {
                return(null);
            }

            IntPtr hicon = Windowing.CopyIcon(cursorInfo.hCursor);

            if (hicon == IntPtr.Zero)
            {
                return(null);
            }

            Windowing.ICONINFO iconInfo;
            if (!Windowing.GetIconInfo(hicon, out iconInfo))
            {
                return(null);
            }

            int x = cursorInfo.ptScreenPos.X - ((int)iconInfo.xHotspot);
            int y = cursorInfo.ptScreenPos.Y - ((int)iconInfo.yHotspot);

            using (Bitmap maskBitmap = Bitmap.FromHbitmap(iconInfo.hbmMask))
            {
                // Is this a monochrome cursor?
                if (maskBitmap.Height == maskBitmap.Width * 2)
                {
                    Bitmap resultBitmap = new Bitmap(maskBitmap.Width, maskBitmap.Width);

                    Graphics desktopGraphics = Graphics.FromHwnd(Windowing.GetDesktopWindow());
                    IntPtr   desktopHdc      = desktopGraphics.GetHdc();

                    IntPtr maskHdc = Windowing.CreateCompatibleDC(desktopHdc);
                    IntPtr oldPtr  = Windowing.SelectObject(maskHdc, maskBitmap.GetHbitmap());

                    using (Graphics resultGraphics = Graphics.FromImage(resultBitmap))
                    {
                        IntPtr resultHdc = resultGraphics.GetHdc();

                        // These two operation will result in a black cursor over a white background.
                        // Later in the code, a call to MakeTransparent() will get rid of the white background.
                        Windowing.BitBlt(resultHdc, 0, 0, 32, 32, maskHdc, 0, 32, Windowing.TernaryRasterOperations.SRCCOPY);
                        Windowing.BitBlt(resultHdc, 0, 0, 32, 32, maskHdc, 0, 0, Windowing.TernaryRasterOperations.SRCINVERT);

                        resultGraphics.ReleaseHdc(resultHdc);
                    }

                    IntPtr newPtr = Windowing.SelectObject(maskHdc, oldPtr);
                    Windowing.DeleteDC(newPtr);
                    Windowing.DeleteDC(maskHdc);
                    desktopGraphics.ReleaseHdc(desktopHdc);

                    // Remove the white background from the BitBlt calls,
                    // resulting in a black cursor over a transparent background.
                    resultBitmap.MakeTransparent(Color.White);
                    return(resultBitmap);
                }
            }

            Icon icon = Icon.FromHandle(hicon);

            return(icon.ToBitmap());
        }
コード例 #13
0
        public Vocoder(
            IBGCStream stream,
            IBGCStream carrierStream,
            double freqLowerBound            = 50.0,
            double freqUpperBound            = 16000.0,
            int bandCount                    = 22,
            int fftSize                      = 4096,
            int overlapRatio                 = 4,
            TransformRMSBehavior rmsBehavior = TransformRMSBehavior.Passthrough)
            : base(stream)
        {
            if (stream.Channels != 1)
            {
                throw new StreamCompositionException(
                          $"Vocoder requires a mono input stream. Input stream has {stream.Channels} channels.");
            }

            if (carrierStream.Channels != 1)
            {
                throw new StreamCompositionException(
                          $"Vocoder requires a mono carrier stream. Carrier stream has {carrierStream.Channels} channels.");
            }

            if (stream.SamplingRate != carrierStream.SamplingRate)
            {
                throw new StreamCompositionException(
                          $"Vocoder requires the sampling rate of the stream and carrierStream to match. {stream.SamplingRate} vs {carrierStream.SamplingRate}.");
            }

            this.carrierStream = carrierStream;

            this.fftSize      = fftSize;
            this.overlapRatio = overlapRatio;
            stepSize          = fftSize / overlapRatio;
            overlapSize       = fftSize - stepSize;

            inputBuffer        = new float[fftSize];
            carrierBuffer      = new float[fftSize];
            outputAccumulation = new double[fftSize];
            cachedSampleBuffer = new float[stepSize];

            carrierFFTBuffer = new Complex64[fftSize];
            signalFFTBuffer  = new Complex64[fftSize];

            amplitudeBuffers   = new Complex64[bandCount][];
            carrierBandBuffers = new Complex64[bandCount][];

            for (int i = 0; i < bandCount; i++)
            {
                amplitudeBuffers[i]   = new Complex64[fftSize];
                carrierBandBuffers[i] = new Complex64[fftSize];
            }

            initialized = false;

            double[] windowTemplate = Windowing.GetHalfWindow64(Windowing.Function.BlackmanHarris, fftSize / 2);

            window = new double[fftSize];
            for (int i = 0; i < fftSize / 2; i++)
            {
                window[i] = windowTemplate[i];
                window[fftSize - i - 1] = windowTemplate[i];
            }

            this.rmsBehavior = rmsBehavior;

            bandFrequencies = GetExponentialDistribution(freqLowerBound, freqUpperBound, bandCount).ToArray();

            outputFactor = 0.5 * Math.Sqrt(fftSize) / overlapRatio;
        }
コード例 #14
0
        public ComposedScreenshot(IntPtr targetWindow, ScreenshotMethod method = ScreenshotMethod.DWM, bool withSolidGlass = true)
            : base(targetWindow, method, withSolidGlass)
        {
            Trace.WriteLine("Creating composed screenshot...", string.Format("ComposedScreenshot.ctor [{0}]", System.Threading.Thread.CurrentThread.Name));

            CursorLocation = Cursor.Position;
            CursorImage    = Core.GetCursor();

            //#32768 is the Windows Menu Class
            // || wc.StartsWith("WindowsForms10.Window.20808");
            var ContextMenus = Windowing.GetChildWindows(Windowing.GetDesktopWindow()).Where(h => Windowing.GetWindowClass(h) == "#32768").ToList();

            if (ContextMenus.Any(h => CaptureRect.IntersectsWith(Helper.GetWindowRectangle(h))))
            {
                Trace.WriteLine(string.Format("Found Win32 {0} menus...", ContextMenus.Count), string.Format("ComposedScreenshot.ctor [{0}]", System.Threading.Thread.CurrentThread.Name));

                CompositionStack.AddRange(ContextMenus.Select(h => Screenshot.FromBitmapRect(Core.ScreenshotWindow(h), Helper.GetWindowRectangle((h)))));
            }
            else
            {
                //If there are no Win32 popup context menus found, but the mouse is over something who's root is the target rect, walk that tree for composition items

                //Check if the thing the mouse is over is different (eg, an overhanging menu)
                IntPtr MouseTargetHandle = Windowing.WindowFromPoint(Cursor.Position);

                //We don't want to do this when we're trying to get popup context menus since they are children of the desktop window,
                //not the target window. However that situation is handled separately above.
                //What we're doing here is looking for overlapping windows, like GTK context menus
                if (Windowing.GetAncestor(MouseTargetHandle, Windowing.GA_ROOTOWNER) == this.TargetHandle) // && !this.TargetRect.Contains(Cursor.Position))
                {
                    Trace.WriteLine(string.Format("Mouse over something else, handle {0}...", MouseTargetHandle), string.Format("ComposedScreenshot.ctor [{0}]", System.Threading.Thread.CurrentThread.Name));

                    while (MouseTargetHandle != TargetHandle && MouseTargetHandle != IntPtr.Zero)
                    {
                        //var MouseTargetWindowRect = Helper.GetWindowRectangle(MouseTargetHandle);
                        //var MouseTargetScreenshot = Core.ScreenshotArea(MouseTargetHandle, MouseTargetWindowRect);

                        //GTK menus seem to have virtually identical parents of themselves, so I initially tried to circumvent this
                        //with a check to prevent any two same rects from being added
                        //though, it's obsolete with the more robust removal below

                        //if (!CompositionStack.Any(ss => ss.TargetRect == MouseTargetWindowRect))
                        //var layer = Screenshot.FromBitmapRect(MouseTargetScreenshot, MouseTargetWindowRect);
                        var layer = new Screenshot(MouseTargetHandle, ScreenshotMethod.GDI, false);
                        CompositionStack.Add(layer);

                        Trace.WriteLine("Added " + layer.TargetHandle.ToString() + "; Class: " + layer.WindowClass, "ComposedScreenshot.ctor");

                        MouseTargetHandle = Windowing.GetParent(MouseTargetHandle);
                    }

                    Trace.WriteLine(string.Format("Added {0} items...", CompositionStack.Count), string.Format("ComposedScreenshot.ctor [{0}]", System.Threading.Thread.CurrentThread.Name));

                    //Remove any rect which is completely inside of another. This is mainly an effort to avoid extra layers,
                    //such as those generated by GTK menus, where some elements appear to be duplicated.
                    var toRemove = CompositionStack.Where(cs => CompositionStack.Any(a => cs != a && a.TargetRect.Contains(cs.TargetRect))).ToList();

                    Trace.WriteLine(string.Format("Removing {0} items...", toRemove.Count), string.Format("ComposedScreenshot.ctor [{0}]", System.Threading.Thread.CurrentThread.Name));

                    //In a case where there's one menu and two identical rects, don't remove both of them, or we'll have nothing to compose
                    if (toRemove.Count == CompositionStack.Count && toRemove.Count > 0)
                    {
                        toRemove.RemoveAt(toRemove.Count - 1);
                    }

                    CompositionStack.RemoveAll(r => toRemove.Contains(r));

                    //If they're all fully inside the window bounds, remove them- probably just regular window elements
                    if (CompositionStack.All(cs => this.TargetRect.Contains(cs.TargetRect)))
                    {
                        Trace.WriteLine(string.Format("Clearing {0} items...", toRemove.Count), string.Format("ComposedScreenshot.ctor [{0}]", System.Threading.Thread.CurrentThread.Name));
                        //CompositionStack.RemoveAll(cs => !cs.WindowClass.StartsWith("WindowsForms10.Window.20808"));
                        CompositionStack.Clear();
                    }
                }
            }

            //Since we compose where first is bottom and last is top, we'll need to reverse what we have so far since we enumerate the other direction
            CompositionStack.Reverse();

            //Base window is always the bottom layer of the composition stack
            CompositionStack.Insert(0, this);

            Trace.WriteLine("Done.", string.Format("ComposedScreenshot.ctor [{0}]", System.Threading.Thread.CurrentThread.Name));
        }
コード例 #15
0
ファイル: StandAlone.cs プロジェクト: ahmed605/ZuneShell.dll
        public static Hashtable Startup(string[] args, string defaultCommandLineSwitch)
        {
            WindowSize windowSize = new WindowSize(1012, 693);
            string     str        = null;
            bool       flag1      = false;
            bool       flag2      = false;
            Hashtable  hashtable  = new Hashtable();
            bool       flag3      = false;

            if (args != null)
            {
                foreach (CommandLineArgument commandLineArgument in CommandLineArgument.ParseArgs(args, defaultCommandLineSwitch))
                {
                    switch (commandLineArgument.Name)
                    {
                    case "gdi":
                        Application.RenderingType = RenderingType.GDI;
                        flag3 = true;
                        break;

                    case "switchtogdi":
                        ClientConfiguration.GeneralSettings.RenderingType = 0;
                        break;

                    case "dx9":
                        Application.RenderingType = RenderingType.DX9;
                        flag3 = true;
                        break;

                    case "size":
                        try
                        {
                            windowSize = ParseSize(commandLineArgument.Value);
                            break;
                        }
                        catch (FormatException ex)
                        {
                            break;
                        }
                        catch (ArgumentException ex)
                        {
                            break;
                        }

                    case "minimized":
                        flag2 = true;
                        break;

                    case "nativeframe":
                        flag1 = true;
                        break;

                    case "animations":
                        try
                        {
                            Application.AnimationsEnabled = bool.Parse(commandLineArgument.Value);
                            break;
                        }
                        catch (FormatException ex)
                        {
                            break;
                        }

                    default:
                        hashtable[commandLineArgument.Name] = commandLineArgument.Value;
                        break;
                    }
                }
            }
            if (ClientConfiguration.GeneralSettings.UseGDI)
            {
                ClientConfiguration.GeneralSettings.RenderingType = 0;
                ClientConfiguration.GeneralSettings.UseGDI        = false;
            }
            if (!flag3)
            {
                Application.RenderingType    = (RenderingType)ClientConfiguration.GeneralSettings.RenderingType;
                Application.RenderingQuality = (RenderingQuality)ClientConfiguration.GeneralSettings.RenderingQuality;
            }
            if (str != null)
            {
                if (str == "ltr")
                {
                    Application.IsRTL = false;
                }
                else if (str == "rtl")
                {
                    Application.IsRTL = true;
                }
            }
            Application.AnimationsEnabled = ClientConfiguration.GeneralSettings.AnimationsEnabled;
            Application.Initialize();
            Application.Window.InitialClientSize = windowSize;
            object obj = Registry.GetValue(ZuneUI.Shell.SettingsRegistryPath, "WindowPosition", null);

            if (obj != null)
            {
                if (obj is string)
                {
                    try
                    {
                        if (!flag2)
                        {
                            Application.Window.SetSavedInitialPosition((string)obj);
                        }
                        else
                        {
                            Application.Window.SetSavedInitialPosition((string)obj, WindowState.Minimized);
                        }
                    }
                    catch (ArgumentException ex)
                    {
                    }
                }
            }
            Application.Window.RespectsStartupSettings = true;
            Application.Window.InitialPositionPolicy   = WindowPositionPolicy.CenterOnWorkArea | WindowPositionPolicy.ConstrainToWorkArea;
            Application.Window.ShowWindowFrame         = flag1;
            Application.Window.SetBackgroundColor(ZuneUI.Shell.WindowColorFromRGB(ClientConfiguration.Shell.BackgroundColor));
            if (!flag2)
            {
                Application.DeferredInvoke(delegate
                {
                    Windowing.ForceSetForegroundWindow(Application.Window.Handle);
                }, DeferredInvokePriority.Low);
            }
            return(hashtable);
        }
コード例 #16
0
 protected override void OnDispose() => windowing = null;
コード例 #17
0
ファイル: SPW_Game.cs プロジェクト: superwills/SPW_Classic
    public SPW()
    {
        graphics = new GraphicsDeviceManager( this );
        Content.RootDirectory = "Content";

        this.IsMouseVisible = true;

        #region creating and adding the game component objects Controller, ScreenWriter, Logger, and Windowing
        // instantiate the Controller
        c = new Controller( this );

        // add it as a component so ITS Update()
        // function will AUTOMATICALLY be called
        // everytime this class's does.
        this.Components.Add( c );
        // OK Hoooooold on.  Did that "component"
        // stuff make any sense?

        // Looking at the definition of
        // the Controller class, notice how it says:

        //   public class Controller : GameComponent

        // This reads "public class Controller is-a GameComponent"

        // So what does that mean?

        // Well, it just means that the Controller promises
        // to have an 'Update()' method within it.

        // Remember how our XNA game rapidly does the following:

        /*

         while( true )
         {
           Update() ;
           Draw() ;
         }

        */

        // When you add a GameComponent object to the Components
        // collection however, this is kind of (very roughly) what happens:

        /*
         while( true )
         {
           Update() ;
           foreach( GameComponent component in this.Components )
         component.Update() ;

           Draw() ;
         }

        */

        // The Update() and Draw() functions that will get called
        // by the XNA framework, will normally only be the Update()
        // and Draw() functions of THIS class (the main game class).

        // Ok so what's this?

        // Add a few more components.
        sw = new ScreenWriter( this );
        this.Components.Add( sw );

        // Here's one that's a bit different!
        // Notice that the ScreenWriter IS-A "DRAWABLEGAMECOMPONENT"

        //    public class ScreenWriter : DrawableGameComponent

        // So this is KIND OF what happens then:
        /*
         while( true )
         {
           Update() ;
           foreach( GameComponent component in this.Components )
         component.Update() ;

           Draw() ;
           foreach( DrawableGameComponent drawable in this.Components )
           {
         drawable.Draw() ;
           }
         }

        */

        // This obviously isn't exactly what happens but I think it
        // communicates the idea.

        // Using GameComponents and DrawableGameComponents
        // are great because they tie up ALL the code
        // to do with one "COMPONENT" of the game into one file.

        logger = new Logger( this, true );
        this.Components.Add( logger );

        // Create the Windowing object.
        // The source code for this system
        // by 'Aaron MacDougall', is on codeplex
        // http://www.codeplex.com/wsx/
        windowing = new Windowing( this );
        #endregion

        // Initialize the game state
        gameState = GameState.TitleScreen;  // let game start @ title screen
        netState = NetState.Disconnected;   //

        // create the world object
        world = new World();

        // set width and height of the backbuffer
        this.graphics.PreferredBackBufferHeight = world.ScreenHeight;
        this.graphics.PreferredBackBufferWidth = world.ScreenWidth;

        // Tell player about how to toggle debug
        Color tBlueViolet = Color.BlueViolet;
        tBlueViolet.A = 0;
        sw[ "more" ] = new StringItem( "Press '8' to toggle debug messages", 40, world.ScreenHeight - 40, 5.0f, Color.Red, tBlueViolet );

        // Start with debug messages not being displayed on screen
        // (press '8' to toggle)
        //ToggleDebug();
    }