CreateGraphics() public method

Drawing stuff
public CreateGraphics ( ) : Graphics
return System.Drawing.Graphics
示例#1
0
        /// <summary>
        /// Метод перестраивающий конечную точку нашего курсора по его перетаскиванию...
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            Point p1;
            Point p2;

            if (((e.Button & System.Windows.Forms.MouseButtons.Left) != 0) && (start != Point.Empty))
            {
                using (Graphics g = view.CreateGraphics())
                {
                    p1 = ((System.Windows.Forms.Control)changedImage).PointToScreen(start);

                    if (end != Point.Empty)
                    {
                        p2 = ((System.Windows.Forms.Control)changedImage).PointToScreen(end);
                        System.Windows.Forms.ControlPaint.DrawReversibleFrame(getRectangleForPoints(p1, p2), Color.Black, System.Windows.Forms.FrameStyle.Dashed);
                    }

                    end.X = e.X;
                    end.Y = e.Y;

                    p2 = ((System.Windows.Forms.Control)changedImage).PointToScreen(end);
                    System.Windows.Forms.ControlPaint.DrawReversibleFrame(getRectangleForPoints(p1, p2), Color.Black, System.Windows.Forms.FrameStyle.Dashed);
                }
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Client");

            string server;
            int port;
            ParseArgs(args, out server, out port);

            var points = Remoting(server, port);

            var frm = new Form();

            var closed = Observable.FromEventPattern(frm, "FormClosed");

            frm.Load += (o, e) =>
            {
                var g = frm.CreateGraphics();

                points.TakeUntil(closed).ObserveOn(frm).Subscribe(pt =>
                {
                    g.DrawEllipse(Pens.Red, pt.X, pt.Y, 1, 1);
                });
            };

            Application.Run(frm);
        }
示例#3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Server");

            int port;
            ParseArgs(args, out port);

            var observer = Remoting(port);

            var frm = new Form();

            frm.Load += (o, e) =>
            {
                var g = frm.CreateGraphics();

                var mme = (from mm in Observable.FromEventPattern<MouseEventArgs>(frm, "MouseMove")
                           select mm.EventArgs.Location)
                          .DistinctUntilChanged()
                          .Do(pt =>
                          {
                              g.DrawEllipse(Pens.Red, pt.X, pt.Y, 1, 1);
                          });

                mme.Subscribe(observer);
            };

            Application.Run(frm);
        }
示例#4
0
        /// <summary>
        /// 窗口截图,包含标题栏和内容区
        /// </summary>
        /// <param name="window">窗口对象</param>
        /// <returns>截图Bitmap对象</returns>
        public static Bitmap CaptureWindow(System.Windows.Forms.Form window)
        {
            Rectangle rc          = new Rectangle(window.Location, window.Size);
            Bitmap    memoryImage = null;

            try
            {
                // Create new graphics object using handle to window.
                using (Graphics graphics = window.CreateGraphics())
                {
                    memoryImage = new Bitmap(rc.Width, rc.Height, graphics);

                    using (Graphics memoryGrahics = Graphics.FromImage(memoryImage))
                    {
                        memoryGrahics.CopyFromScreen(rc.X, rc.Y, 0, 0, rc.Size, CopyPixelOperation.SourceCopy);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Capture failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(memoryImage);
        }
示例#5
0
            public override float GetLogicalPixelSize(swf.Screen screen)
            {
                if (!MonitorDpiSupported)
                {
                    // fallback to slow method if we can't get the dpi from the system
                    using (var form = new System.Windows.Forms.Form {
                        Bounds = screen.Bounds
                    })
                        using (var graphics = form.CreateGraphics())
                        {
                            return((uint)graphics.DpiY / 96f);
                        }
                }
                var mon = MonitorFromPoint(screen.Bounds.Location, MONITOR.DEFAULTTONEAREST);

                // use per-monitor aware dpi awareness to get ACTUAL dpi here
                var oldDpiAwareness = SetThreadDpiAwarenessContextSafe(DPI_AWARENESS_CONTEXT.PER_MONITOR_AWARE_v2);

                uint dpiX, dpiY;

                GetDpiForMonitor(mon, MDT.EFFECTIVE_DPI, out dpiX, out dpiY);

                if (oldDpiAwareness != DPI_AWARENESS_CONTEXT.NONE)
                {
                    SetThreadDpiAwarenessContextSafe(oldDpiAwareness);
                }
                return(dpiX / 96f);
            }
示例#6
0
        /// <summary>
        /// Инициализация игры
        /// </summary>
        /// <param name="form"></param>
        public static void Init(System.Windows.Forms.Form form)
        {
            // Графическое устройство для вывода графики
            Graphics g;

            // Предоставляет доступ к главному буферу графического контекста для текущего приложения
            _context = BufferedGraphicsManager.Current;

            // Создаем объект (поверхность рисования) и связываем его с формой
            g = form.CreateGraphics();

            // Запоминаем размеры формы
            Width  = form.ClientSize.Width;
            Height = form.ClientSize.Height;

            // Связываем буфер в памяти с графическим объектом, чтобы рисовать в буфере
            Buffer = _context.Allocate(g, new Rectangle(0, 0, Width, Height));

            Load();

            form.KeyDown += Form_KeyDown;

            Ship.MessageDie += Finish;
            //подписка на методы ведения записей событий
            WriteLog += WriteLogToConsole;
            WriteLog += WriteLogToFile;

            WriteLog?.Invoke("Начало игры");

            //Timer _timer = new Timer { Interval = 100 };
            //_timer.Interval = 100;
            _timer.Start();
            _timer.Tick += Timer_Tick;
        }
        protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider provider)
        {
            using (Form form1 = new Form())
            {
                form1.Paint += new PaintEventHandler(form1_Paint);

                form1.Text = "Font Visualizer";

                font = (Font)provider.GetObject();

                form1.StartPosition = FormStartPosition.WindowsDefaultLocation;
                form1.SizeGripStyle = SizeGripStyle.Auto;
                form1.ShowInTaskbar = false;
                form1.ShowIcon = false;

                Graphics formGraphics = form1.CreateGraphics();

                var size = formGraphics.MeasureString(font.Name, font);

                form1.Width = (int)size.Width + 100;
                form1.Height = (int)size.Height + 100;

                windowService.ShowDialog(form1);
            }
        }
示例#8
0
        float GetRealScale()
        {
            if (realScale != null)
            {
                return(realScale.Value);
            }

            if (window != null)
            {
                var source = sw.PresentationSource.FromVisual(window);
                if (source != null)
                {
                    realScale = (float)source.CompositionTarget.TransformToDevice.M22;
                    window    = null;
                }
            }

            if (realScale == null)
            {
                using (var form = new swf.Form {
                    Bounds = Control.Bounds
                })
                    using (var graphics = form.CreateGraphics())
                    {
                        realScale = graphics.DpiY / 96f;
                    }
            }
            return(realScale ?? 1f);
        }
示例#9
0
        public void BufferAroundLine()
        {
            var form = new Form {BackColor = Color.White, Size = new Size(500, 200)};

            form.Paint += delegate
                              {

                                  Graphics g = form.CreateGraphics();

                                  List<ICoordinate> vertices = new List<ICoordinate>();

                                  vertices.Add(new Coordinate(0, 4));
                                  vertices.Add(new Coordinate(40, 15));
                                  vertices.Add(new Coordinate(50, 50));
                                  vertices.Add(new Coordinate(100, 62));
                                  vertices.Add(new Coordinate(240, 45));
                                  vertices.Add(new Coordinate(350, 5));

                                  IGeometry geometry = new LineString(vertices.ToArray());

                                  g.DrawLines(new Pen(Color.Blue, 1), GetPoints(geometry));

                                  BufferOp bufferOp = new BufferOp(geometry);
                                  bufferOp.EndCapStyle = BufferStyle.CapButt;
                                  bufferOp.QuadrantSegments = 0;

                                  IGeometry bufGeo = bufferOp.GetResultGeometry(5);

                                  bufGeo = bufGeo.Union(geometry);
                                  g.FillPolygon(new SolidBrush(Color.Pink), GetPoints(bufGeo));
                              };

            WindowsFormsTestHelper.ShowModal(form);
        }
		public WindowsFormsSwapChainPresenter(Form window)
		{
			_width = window.ClientSize.Width;
			_height = window.ClientSize.Height;
			_bitmap = new Bitmap(_width, _height, PixelFormat.Format24bppRgb);
			_graphics = window.CreateGraphics();
		}
示例#11
0
		/// ------------------------------------------------------------------------------------
		public GridSettings()
		{
			ColumnHeaderHeight = -1;
			Columns = new GridColumnSettings[] { };
			using (Form frm = new Form())
			using (Graphics g = frm.CreateGraphics())
				m_currDpi = DPI = g.DpiX;
		}
示例#12
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		///
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public FormSettings()
		{
			Bounds = new Rectangle(0, 0, 0, -1);
			State = FormWindowState.Normal;
			using (Form frm = new Form())
			using (Graphics g = frm.CreateGraphics())
				m_currDpi = DPI = g.DpiX;
		}
示例#13
0
        public ScreenHandler(swf.Screen screen)
        {
            this.Control = screen;
            var form     = new swf.Form();
            var graphics = form.CreateGraphics();

            scale = graphics.DpiY / 72f;
        }
 public void DrawBoard(Form form)
 {
     Graphics g = form.CreateGraphics();
     Pen _pen = new Pen(Color.Black, _linewidth);
     g.DrawLine(_pen, new Point(_outerMargin + _square + _linewidth / 2, _outerMargin), new Point(_outerMargin + _square + _linewidth / 2, _outerMargin + 3 * _square + 2 * _linewidth));
     g.DrawLine(_pen, new Point(_outerMargin + 2 * _square + _linewidth + _linewidth / 2, _outerMargin), new Point(_outerMargin + 2 * _square + _linewidth + _linewidth / 2, _outerMargin + 3 * _square + 2 * _linewidth));
     g.DrawLine(_pen, new Point(_outerMargin, _outerMargin + _square + _linewidth / 2), new Point(_outerMargin + 3 * _square + 2 * _linewidth, _outerMargin + _square + _linewidth / 2));
     g.DrawLine(_pen, new Point(_outerMargin, _outerMargin + 2 * _square + _linewidth + _linewidth / 2), new Point(_outerMargin + 3 * _square + 2 * _linewidth, _outerMargin + 2 * _square + _linewidth + _linewidth / 2));
 }
示例#15
0
        public GameManager(Form f)
        {
            form = f;
            g = f.CreateGraphics();

            u = new Universe(form.Width, form.Height);
            asteroids = new List<Sprite>();

            form.Paint += new PaintEventHandler(form_Paint);
        }
示例#16
0
        public SupportInputColorDialog() : base()
        {
            AllowFullOpen = true;
            FullOpen      = true;
            var f = new System.Windows.Forms.Form();
            var g = f.CreateGraphics();

            dpiX = g.DpiX / 96;
            dpiY = g.DpiY / 96;
        }
示例#17
0
        //Prepare for print and save image
        private void CaptureScreen(Form parent)
        {
            Graphics myGraphics = parent.CreateGraphics();
            formSize = parent.Size;
            bitmap = new Bitmap(formSize.Width, formSize.Height, myGraphics);
            myGraphics.Dispose();

            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.CopyFromScreen(parent.Location.X, parent.Location.Y, 0, 0, formSize);
        }
示例#18
0
 private void LoadContent() {
     form = new Form {
         Size = new Size(Width, Height),
         StartPosition = FormStartPosition.CenterScreen
     };
     formGraphics = form.CreateGraphics();
     camera = new Camera { Position = new Vector(0, 0, 10), Target = Vector.Zero };
     buffer = new GraphicsBuffer(Width, Height, camera);
     meshes = Mesh.FromBabylonModel("Contents/monkey.babylon");
 }
示例#19
0
 public DrawingSystem(Form form, EntityManager manager)
     : base(manager)
 {
     _form = form;
     _form.Invoke(new Action(() =>
     {
         _context = BufferedGraphicsManager.Current;
         _buffer = _context.Allocate(_form.CreateGraphics(), _form.DisplayRectangle);
     }));
 }
示例#20
0
 public static void capture(Form form)
 {
     Graphics g1 = form.CreateGraphics();
     Image MyImage = new Bitmap(form.ClientRectangle.Width, form.ClientRectangle.Height, g1);
     Graphics g2 = Graphics.FromImage(MyImage);
     IntPtr dc1 = g1.GetHdc();
     IntPtr dc2 = g2.GetHdc();
     BitBlt(dc2, 0, 0, form.ClientRectangle.Width, form.ClientRectangle.Height, dc1, 0, 0, 13369376);
     g1.ReleaseHdc(dc1);
     g2.ReleaseHdc(dc2);
     MyImage.Save(@"c:\Captured.jpg", ImageFormat.Jpeg);
     MessageBox.Show("Finished Saving Image");
 }
示例#21
0
 public StylusMouseMux( Form form )
 {
     using ( var fx = form.CreateGraphics() ) {
         FormDpiX = fx.DpiX;
         FormDpiY = fx.DpiY;
     }
     form.MouseDown += OnMouseDown;
     form.MouseMove += OnMouseMove;
     form.MouseUp   += OnMouseUp;
     RTS = new RealTimeStylus(form,true);
     RTS.AsyncPluginCollection.Add(this);
     Form = form;
 }
示例#22
0
 /// <summary>
 /// 根据Form,取得原始彩色图像
 /// </summary>
 /// <param name="frm"></param>
 /// <returns></returns>
 public static Bitmap GetFormImage(Form frm)
 {
     Graphics g = frm.CreateGraphics();
     Size s = frm.Size;
     Bitmap formImage = new Bitmap(s.Width, s.Height, g);
     Graphics mg = Graphics.FromImage(formImage);
     IntPtr dc1 = g.GetHdc();
     IntPtr dc2 = mg.GetHdc();//13369376
     BitBlt(dc2, 0, 0, frm.ClientRectangle.Width, frm.ClientRectangle.Height, dc1, 0, 0, 23369376);
     g.ReleaseHdc(dc1);
     mg.ReleaseHdc(dc2);
     return formImage;
 }
示例#23
0
        public static void Initialize(Form maingame)
        {
            Graphics g = maingame.CreateGraphics();
            Maingame[0] = maingame;
            background[0] = new Background();
            background[0].Draw(g);
            Players.Add(new Player(1));
            Players[0].Draw(g); 
            System.Timers.Timer _timer = new System.Timers.Timer(25);
            _timer.Elapsed += _timer_Elapsed;
            _timer.Enabled = true;
            


        }
 public void TestCreateChildren()
 {
     var bounds = new Rectangle(1920, 0, 1024, 768);
     var screen = new GridScreen(bounds, new HandyMap());
     using (var form = new Form())
     {
         form.Size = new Size(1024, 768);
         screen.CreateChildren(form.CreateGraphics());
         var dic = screen.Root.DicChildren;
         Assert.AreEqual(dic.Count, 9);
         Assert.AreEqual(new Rectangle(0, 0, 341, 256), dic["w"].Bounds);
         Assert.AreEqual(new Rectangle(682, 256, 341, 256), dic["f"].Bounds);
         Assert.AreEqual(new Rectangle(0, 512, 341, 256), dic["x"].Bounds);
     }
 }
示例#25
0
        public static int CalculateCurrentDPI(Form f)
        {
            float dx, dy;
            Graphics g = f.CreateGraphics();
            try
            {
                dx = g.DpiX;
                dy = g.DpiY;
            }
            finally
            {
                g.Dispose();
            }

            return (int)dx;
        }
示例#26
0
 public void TestFullMap()
 {
     var panel = new RootPanel(new Rectangle(0, 0, 100, 200));
     Assert.IsNull(panel.Parent);
     Assert.IsFalse(panel.HasParent);
     Assert.AreEqual(new Rectangle(0, 0, 100, 200), panel.Bounds);
     Assert.AreEqual(new Point(50, 100), panel.CursorPoint);
     Assert.IsNull(panel.DicChildren);
     using (var form = new Form())
     {
         panel.CreateChildren(form.CreateGraphics(), new FullMap());
         Assert.AreEqual(25, panel.DicChildren.Count);
         Assert.AreEqual(new Point(0, 0), panel.DicChildren["q"].MapPosition);
         Assert.AreEqual(new Point(4, 4), panel.DicChildren[";"].MapPosition);
     }
 }
示例#27
0
        public RealtimeWindowOutput(uint width, uint height, Form form)
        {
            Width = width;
              Height = height;

              image = new Bitmap((int)Width, (int)Height);

              this.form = form;
              form.Width = (int)Width;
              form.Height = (int)Height;
              form.FormBorderStyle = FormBorderStyle.FixedSingle;
              form.BackColor = Color.White;
              form.BackgroundImage = image;

              g = form.CreateGraphics();

              func = new MyMethodInvoker(WritePixel);
        }
示例#28
0
        Point topLeftBound, bottomRightBound; //Пределы игрового пространства

        #endregion Fields

        #region Constructors

        public Field(Size fieldSize, Form parentForm)
        {
            //Инициализация
            size = fieldSize;
            form = parentForm;
            //Буферизованная графика
            bufGraphicsCtx.MaximumBuffer = fieldSize;
            bufGraphics = bufGraphicsCtx.Allocate(parentForm.CreateGraphics(), parentForm.ClientRectangle);
            graphics = bufGraphics.Graphics;
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            parentForm.Paint += RedrawField; //Перерисовка мира
            parentForm.KeyDown += KeyPressed; //Событие KeyDown на движение каретки
            RegisterBlocksAndBounds(); //Блоки и пределы
            RegisterCaretAndBall(); //Шар и каретка
            strikingBall.IsMoving = true;
            gameTimer.Interval = 25;
            gameTimer.Tick += GameFrame;
            gameTimer.Start(); //Начало игры
        }
示例#29
0
 public void TestGridPanel()
 {
     using (var form = new Form())
     {
         var g = form.CreateGraphics();
         var panel = new GridPanel(new RootPanel(new Rectangle(0, 0, 1000, 1600)), g, new Point(5, 4), 3, 2, "x");
         Assert.IsNotNull(panel.Parent);
         Assert.IsTrue(panel.HasParent);
         Assert.AreEqual(new Rectangle(600, 800, 200, 400), panel.Bounds);
         Assert.AreEqual(new Point(700, 1000), panel.CursorPoint);
         Assert.IsNull(panel.DicChildren);
         Assert.AreEqual(149, panel.FontSize);
         Assert.IsTrue(panel.IsOdd);
         panel.MapPosition.X = 0;
         Assert.IsFalse(panel.IsOdd);
         panel.CreateChildren(g, new FullMap());
         var child = panel.DicChildren["f"];
         Assert.AreEqual(new Rectangle(720, 880, 40, 80), child.Bounds);
     }
 }
示例#30
0
        /// <summary>
        /// Инициализация обьектов текущей формы
        /// </summary>
        /// <param name="form"></param>
        public static void Init(System.Windows.Forms.Form form)
        {
            //Граф.устройсто для вывода графики
            Graphics g;

            //Предоставляет доступ к главному буферу графического контекста для текущего приложения
            _context = BufferedGraphicsManager.Current;
            // Создаем объект (поверхность рисования) и связываем его с формой
            g = form.CreateGraphics();
            // Запоминаем размеры формы
            Width  = form.ClientSize.Width;
            Height = form.ClientSize.Height;
            // Связываем буфер в памяти с графическим объектом, чтобы рисовать в буфере
            Buffer           = _context.Allocate(g, new Rectangle(0, 0, Width, Height));
            Ship.MessageDie += Finish;
            Ship.MessageWin += Win;
            _timer.Start();
            _timer.Tick  += Timer_Tick;
            form.KeyDown += Form_KeyDown;
            Load();
        }
示例#31
0
文件: Win32.dpi.cs 项目: zzlvff/Eto
        public static uint GetDpi(this System.Windows.Forms.Screen screen)
        {
            if (!MonitorDpiSupported)
            {
                // fallback to slow method if we can't get the dpi from the system
                using (var form = new System.Windows.Forms.Form {
                    Bounds = screen.Bounds
                })
                    using (var graphics = form.CreateGraphics())
                    {
                        return((uint)graphics.DpiY);
                    }
            }

            var  pnt = new System.Drawing.Point(screen.Bounds.Left + 1, screen.Bounds.Top + 1);
            var  mon = MonitorFromPoint(pnt, MONITOR.DEFAULTTONEAREST);
            uint dpiX, dpiY;

            GetDpiForMonitor(mon, MDT.EFFECTIVE_DPI, out dpiX, out dpiY);
            return(dpiX);
        }
示例#32
0
 public static Size GetStringRectangle(Form sender, string source, Font font)
 {
     Size size;
     Graphics graphics = sender.CreateGraphics();
     try
     {
         size = new Size((int) graphics.MeasureString(source, font).Width, (int) graphics.MeasureString(source, font).Height);
     }
     catch
     {
         size = new Size(20, 20);
     }
     finally
     {
         if (graphics != null)
         {
             graphics.Dispose();
         }
     }
     return size;
 }
示例#33
0
        public void InitializeTimeStampColumWidths(Form parentForm)
        {
            if (_settings != null && _settings.General.ListViewColumsRememberSize && _settings.General.ListViewNumberWidth > 1 &&
                _settings.General.ListViewStartWidth > 1 && _settings.General.ListViewEndWidth > 1 && _settings.General.ListViewDurationWidth > 1)
            {
                Columns[ColumnIndexNumber].Width = _settings.General.ListViewNumberWidth;
                Columns[ColumnIndexStart].Width = _settings.General.ListViewStartWidth;
                Columns[ColumnIndexEnd].Width = _settings.General.ListViewEndWidth;
                Columns[ColumnIndexDuration].Width = _settings.General.ListViewDurationWidth;
                Columns[ColumnIndexText].Width = _settings.General.ListViewTextWidth;
                _saveColumnWidthChanges = true;
            }
            else
            {
                Graphics graphics = parentForm.CreateGraphics();
                SizeF timestampSizeF = graphics.MeasureString("00:00:33,527", Font);
                int timeStampWidth = (int)(timestampSizeF.Width + 0.5) + 11;
                Columns[ColumnIndexStart].Width = timeStampWidth;
                Columns[ColumnIndexEnd].Width = timeStampWidth;
                Columns[ColumnIndexDuration].Width = (int)(timeStampWidth * 0.8);
            }

            SubtitleListViewResize(this, null);
        }
示例#34
0
        public void Paint(Graphics g, Rectangle bounds)
        {
            // Lock the sheet and strokes
            using (Synchronizer.Lock(this.m_Sheet.SyncRoot)) {
                using (Synchronizer.Lock(this.m_Sheet.Ink.Strokes.SyncRoot)) {
                    if (this.m_Sheet.Ink.Strokes.Count <= 0)
                    {
                        return;
                    }

                    // Make a copy of the set of all strokes to be painted.
                    // The selected strokes will be removed from this and painted separately.
                    Strokes strokes   = this.m_Sheet.Ink.Strokes;
                    Strokes selection = this.m_Sheet.Selection;

                    if (selection != null)
                    {
                        strokes.Remove(selection);
                    }

                    // Create an image using temporary graphics and graphics buffer object
                    Bitmap imageForPrinting = new Bitmap(bounds.Width, bounds.Height);
                    using (Graphics graphicsImage = Graphics.FromImage(imageForPrinting))
                        using (DibGraphicsBuffer dib = new DibGraphicsBuffer()) {
                            // Create temporary screen Graphics
                            System.Windows.Forms.Form tempForm = new System.Windows.Forms.Form();
                            Graphics screenGraphics            = tempForm.CreateGraphics();
                            // Create temporary Graphics from the Device Independent Bitmap
                            using (Graphics graphicsTemp = dib.RequestBuffer(screenGraphics, bounds.Width, bounds.Height)) {
                                graphicsTemp.Clear(System.Drawing.Color.Transparent);

                                // Draw the unselected ink!
                                // (Ink is not a published property of the InkSheetModel, so no need to obtain a lock.)
                                this.m_Renderer.Draw(graphicsTemp, strokes);

                                if (selection != null)
                                {
                                    // Draw each stroke individually, adjusting its DrawingAttributes.
                                    // TODO: This is very inefficient compared to drawing them all as a group (make a selection of several hundred strokes to see -- a big slow-down).
                                    foreach (Stroke stroke in selection)
                                    {
                                        // It's possible to erase ink while it's selected,
                                        // either with the inverted end of the stylus or via the Undo service.
                                        // But even though the deleted ink won't be part of the main Ink.Strokes collection,
                                        // it won't have been removed from the selection Strokes collection.
                                        // TODO: Being able to delete strokes while they are selected might break more than this.
                                        //   Evaluate what needs to change in the eraser and undo service to make this less hacky.
                                        if (stroke.Deleted)
                                        {
                                            continue;
                                        }

                                        // First draw a highlighted background for all the strokes.
                                        DrawingAttributes atts = stroke.DrawingAttributes.Clone();
                                        float             width = atts.Width, height = atts.Height;
                                        atts.RasterOperation = RasterOperation.CopyPen;
                                        atts.Color           = SystemColors.Highlight;
                                        atts.Width          += SELECTED_BORDER_WIDTH__HIMETRIC;
                                        atts.Height         += SELECTED_BORDER_WIDTH__HIMETRIC;
                                        this.m_Renderer.Draw(graphicsTemp, stroke, atts);
                                    }

                                    foreach (Stroke stroke in selection)
                                    {
                                        if (stroke.Deleted)
                                        {
                                            continue;
                                        }

                                        // Second, draw the stroke itself, but with a contrastive color.
                                        DrawingAttributes atts = stroke.DrawingAttributes.Clone();
                                        atts.RasterOperation = RasterOperation.CopyPen;
                                        atts.Color           = SystemColors.HighlightText;
                                        this.m_Renderer.Draw(graphicsTemp, stroke, atts);
                                    }
                                }

                                // Use the buffer to paint onto the final image
                                dib.PaintBuffer(graphicsImage, 0, 0);

                                // Draw this image onto the printer graphics,
                                // adjusting for printer margins
                                g.DrawImage(imageForPrinting, bounds.Top, bounds.Left);
                            }
                        }
                }
            }
        }
示例#35
0
        private void ScrCapturer_Load(object sender, EventArgs e)
        {
            /*Left = 0;
            Top = 0; */
            MouseRect = Bounds = Screen.GetBounds(new Point());

            AllowTransparency = false;
            Opacity = 0.15;

            MouseFormRect = new Form();
            MouseFormRect.FormBorderStyle = FormBorderStyle.None;
            MouseFormRect.Bounds = this.Bounds;
            MouseFormRect.AllowTransparency = true;
            MouseFormRect.BackColor = Color.Brown;
            MouseFormRect.TransparencyKey = Color.Brown;
            MouseFormRect.Show();

            ScrCapturer_DrawInfor(MouseFormRect.CreateGraphics());
        }
示例#36
0
        // NOTE: Eventually this code should be converted to use SlideRenderer instead of each SheetRenderer. There were some issues with doing
        // this initially so for the time being we will keep it like this.
        public static Bitmap DrawSlide(TableOfContentsModel.Entry currentEntry, System.Drawing.Color background, SheetDisposition dispositions)
        {
            // Save the old state
            System.Drawing.Drawing2D.GraphicsState oldState;

            using (Synchronizer.Lock(currentEntry.Slide.SyncRoot)) {
                Rectangle rect = new Rectangle(0, 0, currentEntry.Slide.Bounds.Width, currentEntry.Slide.Bounds.Height);

                //Note: Uses DibGraphicsBuffer from TPC SDK to do antialiasing
                //See: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dntablet/html/tbconprintingink.asp
                /// create the bitmap we're exporting to
                Bitmap toExport = new Bitmap(rect.Width, rect.Height);
                /// create what we will be drawing on to the export
                Graphics toSave = Graphics.FromImage(toExport);

                /// draw the slide data on a temporary graphics object in a temporary form
                System.Windows.Forms.Form tempForm = new System.Windows.Forms.Form();
                Graphics          screenGraphics   = tempForm.CreateGraphics();
                DibGraphicsBuffer dib          = new DibGraphicsBuffer();
                Graphics          tempGraphics = dib.RequestBuffer(screenGraphics, rect.Width, rect.Height);

                //Add the background color
                //First see if there is a Slide BG, if not, try the Deck.  Otherwise, use transparent.
                tempGraphics.Clear(background);

                //Get the Slide content and draw it
                oldState = tempGraphics.Save();

                Model.Presentation.SlideModel.SheetCollection sheets = currentEntry.Slide.ContentSheets;
                for (int i = 0; i < sheets.Count; i++)
                {
                    Model.Viewer.SlideDisplayModel display = new Model.Viewer.SlideDisplayModel(tempGraphics, null);

                    Rectangle slide = rect;
                    float     zoom  = 1f;
                    if (currentEntry.Slide != null)
                    {
                        slide = currentEntry.Slide.Bounds;
                        zoom  = currentEntry.Slide.Zoom;
                    }

                    System.Drawing.Drawing2D.Matrix pixel, ink;
                    display.FitSlideToBounds(System.Windows.Forms.DockStyle.Fill, rect, zoom, ref slide, out pixel, out ink);
                    using (Synchronizer.Lock(display.SyncRoot)) {
                        display.SheetDisposition = dispositions;
                        display.Bounds           = slide;
                        display.PixelTransform   = pixel;
                        display.InkTransform     = ink;
                    }

                    Viewer.Slides.SheetRenderer r = Viewer.Slides.SheetRenderer.ForStaticSheet(display, sheets[i]);
                    if ((r.Sheet.Disposition & dispositions) != 0)
                    {
                        r.Paint(new System.Windows.Forms.PaintEventArgs(tempGraphics, rect));
                    }
                    r.Dispose();
                }

                //Restore the Old State
                tempGraphics.Restore(oldState);
                oldState = tempGraphics.Save();

                //Get the Annotation content and draw it
                sheets = currentEntry.Slide.AnnotationSheets;
                for (int i = 0; i < sheets.Count; i++)
                {
                    Model.Viewer.SlideDisplayModel display = new Model.Viewer.SlideDisplayModel(tempGraphics, null);

                    Rectangle slide = rect;
                    float     zoom  = 1f;
                    if (currentEntry.Slide != null)
                    {
                        slide = currentEntry.Slide.Bounds;
                        zoom  = currentEntry.Slide.Zoom;
                    }

                    System.Drawing.Drawing2D.Matrix pixel, ink;
                    display.FitSlideToBounds(System.Windows.Forms.DockStyle.Fill, rect, zoom, ref slide, out pixel, out ink);
                    using (Synchronizer.Lock(display.SyncRoot)) {
                        display.SheetDisposition = dispositions;
                        display.Bounds           = slide;
                        display.PixelTransform   = pixel;
                        display.InkTransform     = ink;
                    }

                    Viewer.Slides.SheetRenderer r = Viewer.Slides.SheetRenderer.ForStaticSheet(display, sheets[i]);
                    if ((r.Sheet.Disposition & dispositions) != 0)
                    {
                        r.Paint(new System.Windows.Forms.PaintEventArgs(tempGraphics, rect));
                    }
                    r.Dispose();
                }

                //Restore the Old State
                tempGraphics.Restore(oldState);

                //Export the image
                //Merge the graphics
                dib.PaintBuffer(toSave, 0, 0);

                //Dispose all the graphics
                toSave.Dispose();
                screenGraphics.Dispose();
                tempGraphics.Dispose();

                return(toExport);
            }
        }
示例#37
0
            internal Window(Screensaver screensaver, Form form)
            {
                this.screensaver = screensaver;
                this.form = form;
                this.size = form.ClientSize;
                this.graphics = form.CreateGraphics();
                this.handle = form.Handle;

                form.KeyPress += new KeyPressEventHandler(form_KeyPress);

                this.screensaver.PostUpdate += new EventHandler(screensaver_PostUpdate);
            }
示例#38
0
 public override void Draw(Form f)
 {
     Graphics graphics = f.CreateGraphics();
     try
         {
             graphics.DrawImage( _frames[(int) this.current], size * i, size * j, size, size);
         }
     catch (Exception ex)
     {
        MessageBox.Show(ex.Message + ex.Source);
     }
 }
示例#39
0
            internal Window(Screensaver screensaver, Form form)
            {
                this.screensaver = screensaver;
                this.form = form;
                this.size = form.ClientSize;
                this.graphics = form.CreateGraphics();
                this.handle = form.Handle;

                form.MouseMove += new MouseEventHandler(form_MouseMove);
                form.MouseClick += new MouseEventHandler(form_MouseClick);
                form.MouseDoubleClick += new MouseEventHandler(form_MouseDoubleClick);
                form.MouseDown += new MouseEventHandler(form_MouseDown);
                form.MouseUp += new MouseEventHandler(form_MouseUp);
                form.MouseWheel += new MouseEventHandler(form_MouseWheel);

                form.KeyDown += new KeyEventHandler(form_KeyDown);
                form.KeyUp += new KeyEventHandler(form_KeyUp);
                form.KeyPress += new KeyPressEventHandler(form_KeyPress);

                this.screensaver.PreUpdate += new EventHandler(screensaver_PreUpdate);
                this.screensaver.PostUpdate += new EventHandler(screensaver_PostUpdate);
            }
示例#40
0
        public static void SaveFont(string strFileBitmap, Palette pal, string strFileAscii, string strFileSave)
        {
            // Get the character order
            TextReader tr = new StreamReader(strFileAscii);
            string strAscii = tr.ReadLine();
            tr.Close();

            // Get the character count
            int cch = strAscii.Length;

            // Load the image, lose scaling factor
            Bitmap bmFile = new Bitmap(strFileBitmap);
            Bitmap bm = Misc.NormalizeBitmap(bmFile);
            bmFile.Dispose();

            // Turn this on to see the character -> glyph mapping as it happens (help for
            // finding 'font bugs'). Set a breakpoint below on frm.Dispose().

            #if SHOWFONT
            Form frm = new Form();
            frm.Height = 1000;
            frm.Show();
            Graphics gT = frm.CreateGraphics();
            gT.InterpolationMode = InterpolationMode.NearestNeighbor;
            int yDst = 0;
            int xDst = 0;
            #endif
            // Scan the bitmap for widths
            int xLast = 0;
            int ich = 0;
            byte[] acxChar = new byte[256];
            for (int x = 0; x < bm.Width; x++) {
                if (bm.GetPixel(x, 0) != Color.FromArgb(255, 0, 255)) {
                    Debug.Assert(ich < cch);
                    acxChar[strAscii[ich]] = (byte)(x - xLast);
            #if SHOWFONT
                    gT.DrawString(strAscii[ich].ToString(), frm.Font, new SolidBrush(frm.ForeColor), new PointF(xDst, yDst));
                    Rectangle rcDst = new Rectangle(xDst + 20, yDst + 2, (x - xLast), bm.Height);
                    Rectangle rcSrc = new Rectangle(xLast, 1, x - xLast, bm.Height);
                    gT.DrawImage(bm, rcDst, rcSrc, GraphicsUnit.Pixel);
                    yDst += Math.Max(bm.Height, frm.Font.Height);
                    if (yDst > frm.ClientRectangle.Height) {
                        xDst += 50;
                        yDst = 0;
                    }

                    gT.Flush();
                    Application.DoEvents();
            #endif
                    ich++;
                    xLast = x;
                }
            }
            #if SHOWFONT
            gT.Dispose();
            frm.Dispose();
            #endif

            if (ich != cch) {
                MessageBox.Show(String.Format("Expecting {0} characters but found {2}{1}.",
                        cch, ich, ich < cch ? "only " : ""), "bcr2 - Font Compilation Error");
                Debug.Assert(ich == cch - 1);
            }
            int cy = bm.Height - 1;

            // Save serialization
            ArrayList alsSdEven = new ArrayList();
            int xT = 0;
            int ichDefault = -1;
            for (ich = 0; ich < cch; ich++) {
                // ? is the default "no glyph" character
                if (strAscii[ich] == '?')
                    ichDefault = ich;

                // Get subimage
                int cx = acxChar[strAscii[ich]];
                Rectangle rcT = new Rectangle(xT, 1, cx, cy);
                xT += cx;
                Bitmap bmT = new Bitmap(cx, cy, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(bmT);
                g.DrawImage(bm, 0, 0, rcT, GraphicsUnit.Pixel);
                g.Dispose();

                // Compile scan data
                TBitmap tbm = new TBitmap(bmT, pal);
                bmT.Dispose();

                // Save scan data serialization
                alsSdEven.Add(tbm.SerializeScanData());
            }

            //FontHeader {
            //	word cy;
            //	byte acxChar[256];
            //	word mpchibsdEven[256];
            //	ScanData asd[1];
            //};

            // First serialize scan data

            ArrayList alsIbsdEven = new ArrayList();
            ArrayList alsSd = new ArrayList();
            foreach (byte[] absd in alsSdEven) {
                if ((alsSd.Count & 1) != 0)
                    alsSd.Add((byte)0);
                alsIbsdEven.Add(alsSd.Count);
                alsSd.AddRange(absd);
            }

            // Write out to file
            BinaryWriter bwtr = new BinaryWriter(new FileStream(strFileSave, FileMode.Create, FileAccess.Write));

            // Height
            bwtr.Write(Misc.SwapUShort((ushort)cy));

            // Ascii ordered char widths in bytes. First init 0's to width of '?'

            if (ichDefault != -1) {
                for (ich = 0; ich < acxChar.Length; ich++) {
                    if (acxChar[ich] == 0) {
                        acxChar[ich] = acxChar[strAscii[ichDefault]];
                    }
                }
            }
            bwtr.Write(acxChar);

            // Ascii ordered offsets to even scan data (even)
            // Fill unused entries to entry for '?'
            int[] aibsdEven = new int[256];
            for (int ibsd = 0; ibsd < aibsdEven.Length; ibsd++)
                aibsdEven[ibsd] = -1;
            for (int i = 0; i < cch; i++)
                aibsdEven[strAscii[i]] = (int)alsIbsdEven[i];
            if (ichDefault != -1) {
                for (int ibsd = 0; ibsd < aibsdEven.Length; ibsd++) {
                    if (aibsdEven[ibsd] == -1) {
                        aibsdEven[ibsd] = (int)alsIbsdEven[ichDefault];
                    }
                }
            }

            // Write it out
            int cbHeader = 2 + 256 + 512;
            for (int i = 0; i < 256; i++)
                bwtr.Write(Misc.SwapUShort((ushort)(cbHeader + aibsdEven[i])));

            // Now save scan data
            bwtr.Write((byte[])alsSd.ToArray(typeof(byte)));

            // Done
            bwtr.Close();
        }
示例#41
0
        //my personal splashscreen method
        public void SplashScreen()
        {
            //makes form invisible
            Form ss = new Form();
            ss.FormBorderStyle = FormBorderStyle.None;
            ss.Size = new Size(400, 400);
            ss.StartPosition = FormStartPosition.CenterScreen;
            ss.BackColor = Color.Red;
            ss.TransparencyKey = Color.Red;

            ss.Show();

            Graphics ssGraphics = ss.CreateGraphics();
            SolidBrush ssBrush = new SolidBrush(Color.DarkBlue);
            Font ssFont = new Font("Liberation Mono", 30, FontStyle.Bold);  //font for my name
            Font subtitles = new Font("Liberation Mono", 20);               //font for subtitles.
            ssGraphics.FillEllipse(ssBrush, 0, 0, 400, 400);

            Thread.Sleep(2000);

            //causes the "a" to descend
            for (int i = -50; i < 50; i += 2)
            {
                ssBrush.Color = Color.DarkBlue;
                ssGraphics.FillEllipse(ssBrush, 0, 0, 400, 400);

                ssBrush.Color = Color.Blue;
                ssGraphics.FillEllipse(ssBrush, 180, i, 50, 50);

                ssBrush.Color = Color.LightCyan;
                ssGraphics.DrawString("A", subtitles, ssBrush, 190, i + 10);
                Thread.Sleep(5);

            }

            ssBrush.Color = Color.White;

            //causes my name to rotate in
            for (int i = 90; i > 0; i--)
            {

                ssBrush.Color = Color.DarkBlue;
                ssGraphics.FillEllipse(ssBrush, 0, 0, 400, 400);

                ssBrush.Color = Color.Blue;
                ssGraphics.FillEllipse(ssBrush, 180, 50, 50, 50);

                ssBrush.Color = Color.LightCyan;
                ssGraphics.DrawString("A", subtitles, ssBrush, 190, 60);

                ssBrush.Color = Color.White;
                ssGraphics.TranslateTransform(200, 50);
                ssGraphics.RotateTransform(i);//rotates canvas before drawing name
                ssGraphics.DrawString("Gareth Marks", ssFont, ssBrush, -150, 100); //draws my name
                ssGraphics.ResetTransform();//resets rotation

                Thread.Sleep(5);
            }

            string[] letters = { "p", "r", "o", "d", "u", "c", "t", "i", "o", "n", "s", }; //array to hold letters

            ssBrush.Color = Color.Cyan;

            for (int i = 0; i < 10; i++)
            {
                ssGraphics.DrawString(letters[i], subtitles, ssBrush, i * 18 + 70, 200);//causes productions to appear one letter at a time
                Thread.Sleep(200);
            }

            for (int i = 50; i < 200; i++)
            {
                ssGraphics.FillRectangle(ssBrush, i, 330, 3, 3);
                ssGraphics.FillRectangle(ssBrush, 400 - i, 330, 3, 3);//causes "loading bars" to fill in at the end
                Thread.Sleep(10);
            }
            Thread.Sleep(3000);
        }