Converts the attributes of this to a human readable string.
private void pictureBox1_MouseClick(object sender, MouseEventArgs e) { IconRect = GetCurrenIconRect(); IconID = GetCurrenIconID(); label1.Text = IconID.ToString(); label2.Text = IconRect.ToString(); }
public Bitmap CaptureScreenShot() { Logger.record("[CaptureScreenshot]: Will take a screenshot of the monitor.", "ScreenShot", "info"); Rectangle fullBounds = new Rectangle(); int minX = 0, minY = 0, maxX = 0, maxY = 0; /* * Composite desktop calculations for multiple monitors A, B E, B || E, B +--------------+ || * +---------------+ D, B | |E, G || | | | +---------------+ D, G || +--------------+ E, C | | | | || |A, C | | | | | || | | | | | | || | | | +--------------+ E, C | || | +---------------+ D, G A, C | | || | |E, G +---------------+ D, F || +--------------+ * E, F || A, F E, F * We capture from "A, B" to "D, F". * That is, we look for the minimum X,Y coordinate first. * Then we look for the largest width,height. */ foreach (Screen oneScreen in Screen.AllScreens) { Logger.record("\t[CaptureScreenshot]: AllScreens[]: " + oneScreen.Bounds.ToString(), "ScreenShot", "info"); minX = Math.Min(minX, oneScreen.Bounds.Left); minY = Math.Min(minY, oneScreen.Bounds.Top); maxX = Math.Max(maxX, oneScreen.Bounds.Width + oneScreen.Bounds.X); maxY = Math.Max(maxY, oneScreen.Bounds.Height + oneScreen.Bounds.Y); } fullBounds = new Rectangle(minX, minY, maxX - minX, maxY - minY); Logger.record("[CaptureScreenshot]: fullScreen[]: " + fullBounds.ToString(), "ScreenShot", "info"); IntPtr hDesk = GetDesktopWindow(); IntPtr hSrce = GetWindowDC(hDesk); IntPtr hDest = CreateCompatibleDC(hSrce); // Our bitmap will have the size of the composite screenshot IntPtr hBmp = CreateCompatibleBitmap(hSrce, fullBounds.Width, fullBounds.Height); IntPtr hOldBmp = SelectObject(hDest, hBmp); // We write on coordinate 0,0 of the bitmap buffer, of course. But we write the the fullBoundsX,Y pixels. bool b = BitBlt(hDest, 0, 0, fullBounds.Width, fullBounds.Height, hSrce, fullBounds.X, fullBounds.Y, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt); Bitmap bmp = Bitmap.FromHbitmap(hBmp); SelectObject(hDest, hOldBmp); DeleteObject(hBmp); DeleteDC(hDest); ReleaseDC(hDesk, hSrce); Logger.record("[CaptureScreenshot]: BMP object ready, returning it to calling function", "ScreenShot", "info"); return (bmp); }
public GraphEdit() { InitializeComponent(); this.WindowState = FormWindowState.Maximized; this.m_stGraphs = this.CreateGraphics(); //实例化Graphics类 this.m_stPen = new Pen(Color.Red, 3); //实例化Pen类 this.m_vTaskList = new List <TaskInfo>(); System.Drawing.Rectangle rect = System.Windows.Forms.Screen.PrimaryScreen.Bounds; statusLabel.Text = rect.ToString(); AutoScrollMinSize = new Size(m_stScrollPoint.X, m_stScrollPoint.Y); }
private Bitmap SnapshotRect(System.Drawing.Rectangle rect) { // Allow user to do whatever just before snapshot (Hover, click, presskey, ...) if (BeforeSnapshot != null) { BeforeSnapshot(this, new DoWorkEventArgs(_counter)); } // Take Snapshot Microsoft.Test.Logging.GlobalLog.LogStatus("Capturing rect : " + rect.ToString()); return(ImageUtility.CaptureScreen(rect)); }
//By James Palmisano //last edited 1/23/14 //Purpose of app is to show inheritence. public Form1() { InitializeComponent(); //make instance of rectangle class Rectangle rect = new Rectangle(); rectangleInfo.Text = rect.ToString(); areaOfRectangle.Text = "The area of the retangle is: " + Convert.ToString(rect.Area); //make instance of the circle class Circle cir = new Circle(); circleInfo.Text = cir.ToString(); circleArea.Text = "The area of the circle is: " + Convert.ToString(cir.Area); }
public Screenshot(Rectangle r) { this.Method = ScreenshotMethod.GDI; this.TargetRect = r; this.isMaximized = false; this.TargetScreen = Screen.FromRectangle(r); this.BaseScreenshotImage = Core.ScreenshotArea(r); this.isRounded = false; this.WindowTitle = "Screenshot (" + r.ToString() + ")"; this.Date = DateTime.Now; }
public void test1() { Rectangle rect = new Rectangle(10, 12, 14, 16); // Wrong System.ComponentModel.TypeConverter baseConverter = new System.ComponentModel.TypeConverter(); string sample1 = baseConverter.ConvertToString(rect); // Right System.ComponentModel.TypeConverter rectSpecificConverter = TypeDescriptor.GetConverter(rect); string sample2 = rectSpecificConverter.ConvertToString(rect); log.DebugFormat("From new TypeConverter() {0}\r\n", sample1); log.DebugFormat("From TypeDescriptor.GetConverter() {0}\r\n", sample2); log.DebugFormat("From rect.ToString() {0}\r\n", rect.ToString()); }
private void panel1_MouseMove(object sender, MouseEventArgs e) { Rectangle rect1 = new Rectangle(0, 0, e.Location.X, e.Location.Y); Text = rect1.ToString(); Graphics g = panel1.CreateGraphics(); x = (rect1.Width - 2) / 20 + 1; y = (rect1.Height - 2) / 20 + 1; if (e.Location.X == 0 || e.Location.Y == 0 || e.Location.X < 2 || e.Location.Y < 2) { x = 0; y = 0; } if (x > 8) x = 8; if (y > 7) y = 7; labelMsg.Text = string.Format("{0} x {1}", x, y); for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { Rectangle rect2 = new Rectangle(1 + 1 + 20 * i, 1 + 1 + j * 20, 17, 17); Brush brush1 = new SolidBrush(Color.White); if (rect1.IntersectsWith(rect2)) brush1 = new SolidBrush(SystemColors.Highlight); g.FillRectangle(brush1, rect2); } } g.Dispose(); }
static void Main(string[] args) { int bufSize = 256; StringBuilder sb = new StringBuilder(bufSize); Rectangle rect = new Rectangle(0, 0, 100, 100); if (SetNHW32()) { { for (;;) { int i = 1; int j = 0; Point cursorPoint = new Point(); GetCursorPos(ref cursorPoint); BL_SetFlag32((uint)GetWordFlag.enable, IntPtr.Zero, cursorPoint.X, cursorPoint.Y); Thread.Sleep(1000); BL_GetText32(sb, bufSize, ref rect); System.Console.WriteLine(sb.ToString() + " " + rect.ToString() + " " + cursorPoint.ToString()); } } } }
public Bitmap Clone(Rectangle rect, PixelFormat format) { if (rect.Width == 0 || rect.Height == 0) { throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString())); } IntPtr dstHandle = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneBitmapAreaI( rect.X, rect.Y, rect.Width, rect.Height, unchecked ((int)format), new HandleRef(this, nativeImage), out dstHandle); if (status != SafeNativeMethods.Gdip.Ok || dstHandle == IntPtr.Zero) { throw SafeNativeMethods.Gdip.StatusException(status); } return(FromGDIplus(dstHandle)); }
private void pictureBox1_MouseWheel(object sender, MouseEventArgs e) { //this.Text = counter++.ToString(); if (!showHotRectFlag) return; if (lockHotRect) return; int x = pictureBox1.Left; int y = pictureBox1.Top; int w = 1; int h = 1; Point point = e.Location; point.X -= 6; point.Y -= (mainToolStrip.Height + 24); point.X = (int)((double)point.X / currentViewScale); point.Y = (int)((double)point.Y / currentViewScale); Point pp = new Point(point.X, point.Y ); if (e.Delta > 0) { w =(int) ((double)hotRect.Width * scaleRatio); h = (int)((double)hotRect.Height * scaleRatio); } else { w = (int)((double)hotRect.Width / scaleRatio); h = (int)((double)hotRect.Height / scaleRatio); } if (w < minRectSize || h < minRectSize) { w = Math.Max(minRectSize, w); h = Math.Max(minRectSize, h); } double r = (double)w / (double)h; if (r > hotRectWidthToHeightRatio) w = (int)((double)h * hotRectWidthToHeightRatio); else h = (int)((double)w / hotRectWidthToHeightRatio); hotRect = new Rectangle(pp.X - w / 2, pp.Y - h / 2, w, h); this.Text = hotRect.ToString(); UpdateView(); }
/* * GetGrayscaleBitmap */ /// <summary> /// Converts the specified <see cref="Bitmap"/> to grayscale image. /// </summary> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="sourceBitmap"/> is <see langword="null"/>. /// </exception> public static Bitmap GetGrayscaleBitmap(Bitmap sourceBitmap) { if (sourceBitmap == null) { throw new ArgumentNullException("bmp"); } Bitmap bufferBmp = new Bitmap(sourceBitmap); Rectangle bufferBmpRectangle = new Rectangle(0, 0, bufferBmp.Width, bufferBmp.Height); ImageLockMode imgLockMode = ImageLockMode.ReadWrite; PixelFormat pixelFormat = PixelFormat.Format32bppArgb; if (_infoEnabled) { Trace.TraceInformation("bufferBmpRectangle = {0}", bufferBmpRectangle.ToString()); } BitmapData bmpData = null; try { bmpData = bufferBmp.LockBits(bufferBmpRectangle, imgLockMode, pixelFormat); } catch (Exception e) { if (_errorEnabled) { Trace.TraceError("Error occured while bufferBmp.LockBits operation: {0}", e.Message); } return null; } unsafe { uint* scan0 = (uint*)bmpData.Scan0; for (int height = 0; height < bufferBmp.Height; height++) { for (int width = 0; width < bufferBmp.Width; width++) { int block1 = (bmpData.Stride * height) / 4; uint block2 = scan0[block1 + width]; uint block3 = (block2 >> 0x10) & 0xff; uint block4 = (block2 >> 8) & 0xff; uint block5 = block2 & 0xff; uint block6 = (block3 + block4 + block5) / 3; scan0[block1 + width] = ((block6 << 0x10) + (block6 << 8)) + block6; } } } try { bufferBmp.UnlockBits(bmpData); } catch (Exception e) { if (_errorEnabled) { Trace.TraceError("Error occured while buffer.UnlockBits operation: {0}", e.Message); } return null; } return bufferBmp; }
private void SelectHandle() { WindowState = FormWindowState.Minimized; bool capturing = false; try { Thread.Sleep(250); SimpleWindowInfo simpleWindowInfo = GetWindowInfo(); if (simpleWindowInfo != null) { selectedWindow = new WindowInfo(simpleWindowInfo.Handle); lblControlText.Text = selectedWindow.ClassName ?? string.Empty; selectedRectangle = simpleWindowInfo.Rectangle; lblSelectedRectangle.Text = selectedRectangle.ToString(); btnSelectRectangle.Enabled = btnCapture.Enabled = true; if (Options.StartCaptureAutomatically) { capturing = true; StartCapture(); } } else { btnCapture.Enabled = false; } } finally { if (!capturing) this.ForceActivate(); } }
public void InvalidateEventsOrder () { Rectangle rect = new Rectangle (new Point (0,0), new Size (2, 2)); Form myform = new Form (); myform.ShowInTaskbar = false; myform.Visible = true; MyLabelInvalidate l = new MyLabelInvalidate (); myform.Controls.Add (l); l.TextAlign = ContentAlignment.TopRight; string [] EventsWanted = { "OnHandleCreated", "OnBindingContextChanged", "OnBindingContextChanged", "OnInvalidated,{X=0,Y=0,Width="+l.Size.Width+",Height="+l.Size.Height+"}", "OnInvalidated," + rect.ToString () }; l.Invalidate (rect); Assert.AreEqual (EventsWanted, ArrayListToString (l.Results)); myform.Dispose(); }
/// <summary> /// Paints the Row at the specified index /// </summary> /// <param name="e">A PaintEventArgs that contains the event data</param> /// <param name="row">The index of the Row to be painted</param> /// <param name="rowRect">The bounding Rectangle of the Row to be painted</param> protected void OnPaintRow(PaintEventArgs e, int row, Rectangle rowRect) { Rectangle cellRect = new Rectangle(rowRect.X, rowRect.Y, 0, rowRect.Height); int colsToIgnore = 0; // Used to skip cells that are ignored because of a colspan var nColumns = this.ColumnModel.Columns.Count; var gridLineFlags = new bool[nColumns]; for (int i = 0; i < nColumns; i++) { if (!this.ColumnModel.Columns[i].Visible) { continue; } Cell cell = this.TableModel[row, i]; if (colsToIgnore == 0) { cellRect.Width = this.ColumnModel.Columns[i].Width; // Cope with missing cells in a row if (cell == null) { cell = new Cell(); } // If this cell spans other columns, then the width (above) needs to take into account // the spanned columns too. if (cell.ColSpan > 1) { for (int span = 1; span < cell.ColSpan; span++) { cellRect.Width += this.ColumnModel.Columns[i + span].Width; } } if (cellRect.IntersectsWith(e.ClipRectangle)) { try { this.OnPaintCell(e, row, i, cellRect); } catch (Exception exception) { exception.Data.Add("row", row); exception.Data.Add("column", i); exception.Data.Add("cellRect", cellRect.ToString()); throw; } } else if (cellRect.Left > e.ClipRectangle.Right) { break; } // Ignore the cells that this cell span over if (cell.ColSpan > 1) { colsToIgnore = cell.ColSpan - 1; } } else { colsToIgnore--; // Skip over this cell and count down } gridLineFlags[i] = colsToIgnore < 1; cellRect.X += this.ColumnModel.Columns[i].Width; } Row r = this.TableModel.Rows[row]; if (r.InternalGridLineFlags == null) { r.InternalGridLineFlags = gridLineFlags; } }
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { bool skipMessage = false; Rectangle newBounds = new Rectangle(x, y, width, height); if (GUIGraphicsContext._useScreenSelector && isMaximized) { if (!newBounds.Equals(GUIGraphicsContext.currentScreen.Bounds)) { skipMessage = true; } } if (skipMessage) { Log.Info("d3dapp: Screenselector: skipped SetBoundsCore {0} does not match {1}", newBounds.ToString(), GUIGraphicsContext.currentScreen.Bounds.ToString()); } else { base.SetBoundsCore(x, y, width, height, specified); } }
public virtual int PaintData(Graphics g, Rectangle bounds, int firstVisibleColumn, int columnCount, bool alignToRight) { Debug.WriteLineIf(CompModSwitches.DGRowPaint.TraceVerbose, "Painting DataGridAddNewRow: bounds = " + bounds.ToString()); Rectangle cellBounds = bounds; int bWidth = this.dgTable.IsDefault ? this.DataGrid.GridLineWidth : this.dgTable.GridLineWidth; int cx = 0; DataGridCell current = this.dgTable.DataGrid.CurrentCell; GridColumnStylesCollection columns = dgTable.GridColumnStyles; int nCols = columns.Count; for (int col = firstVisibleColumn; col < nCols; ++col) { if (cx > bounds.Width) break; // if (!columns[col].Visible || columns[col].PropertyDescriptor == null) if (columns[col].PropertyDescriptor == null || columns[col].Width <= 0) continue; cellBounds.Width = columns[col].Width - bWidth; if (alignToRight) cellBounds.X = bounds.Right - cx - cellBounds.Width; else cellBounds.X = bounds.X + cx; // Paint the data with the the DataGridColumn Brush backBr = BackBrushForDataPaint(ref current, columns[col], col); Brush foreBrush = ForeBrushForDataPaint(ref current, columns[col], col); PaintCellContents(g, cellBounds, columns[col], backBr, foreBrush, alignToRight); // Paint the border to the right of each cell if (bWidth > 0) { g.FillRectangle(this.dgTable.IsDefault ? this.DataGrid.GridLineBrush : this.dgTable.GridLineBrush, alignToRight ? cellBounds.X - bWidth : cellBounds.Right, cellBounds.Y, bWidth, cellBounds.Height); } cx += cellBounds.Width + bWidth; } // Paint any exposed area to the right ( or left ) of the data cell area if (cx < bounds.Width) { g.FillRectangle(this.dgTable.DataGrid.BackgroundBrush, alignToRight ? bounds.X : bounds.X + cx, bounds.Y, bounds.Width - cx, bounds.Height); } return cx; }
/// <include file='doc\DataGridRelationshipRow.uex' path='docs/doc[@for="DataGridRelationshipRow.PaintPlusMinusGlyph"]/*' /> /// <internalonly/> private void PaintPlusMinusGlyph(Graphics g, Rectangle bounds, Brush backBr, bool alignToRight) { if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) Debug.WriteLine("PlusMinusGlyph painting in bounds -> " + bounds.ToString()); Rectangle outline = GetOutlineRect(bounds.X, bounds.Y); outline = Rectangle.Intersect(bounds, outline); if (outline.IsEmpty) return; g.FillRectangle(backBr, bounds); if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) Debug.WriteLine("Painting PlusMinusGlyph with outline -> " + outline.ToString()); // draw the +/- box Pen drawPen = this.dgTable.IsDefault ? this.DataGrid.HeaderForePen : this.dgTable.HeaderForePen; g.DrawRectangle(drawPen, outline.X, outline.Y, outline.Width - 1, outline.Height - 1); int indent = 2; // draw the - g.DrawLine(drawPen, outline.X + indent, outline.Y + outline.Width / 2, outline.Right - indent - 1, outline.Y + outline.Width/2); // -1 on the y coordinate if (!expanded) { // draw the vertical line to make + g.DrawLine(drawPen, outline.X + outline.Height/2, outline.Y + indent, outline.X + outline.Height/2, outline.Bottom - indent - 1); // -1... hinting } else { Point[] points = new Point[3]; points[0] = new Point(outline.X + outline.Height/2, outline.Bottom); points[1] = new Point(points[0].X, bounds.Y + 2*indent + base.Height); points[2] = new Point(alignToRight ? bounds.X : bounds.Right, points[1].Y); g.DrawLines(drawPen, points); } }
public override int Paint(Graphics g, Rectangle bounds, // negative offsetted row bounds Rectangle trueRowBounds, // real row bounds. int firstVisibleColumn, int numVisibleColumns, bool alignToRight) { if (CompModSwitches.DGRelationShpRowPaint.TraceVerbose) Debug.WriteLine("Painting row " + RowNumber.ToString(CultureInfo.InvariantCulture) + " with bounds " + bounds.ToString()); int bWidth = this.dgTable.BorderWidth; // paint the data cells Rectangle dataBounds = bounds; dataBounds.Height = base.Height - bWidth; int dataWidth = PaintData(g, dataBounds, firstVisibleColumn, numVisibleColumns, alignToRight); int dataWidthOffsetted = dataWidth + bounds.X - trueRowBounds.X; dataBounds.Offset(0, bWidth); // use bWidth, not 1 if (bWidth > 0) PaintBottomBorder(g, dataBounds, dataWidth, bWidth, alignToRight); if (expanded && this.dgTable.RelationsList.Count > 0) { // paint the relationships Rectangle relationBounds = new Rectangle(trueRowBounds.X, dataBounds.Bottom, trueRowBounds.Width, trueRowBounds.Height - dataBounds.Height - 2 * bWidth); PaintRelations(g, relationBounds, trueRowBounds, dataWidthOffsetted, firstVisibleColumn, numVisibleColumns, alignToRight); relationBounds.Height += 1; if (bWidth > 0) PaintBottomBorder(g, relationBounds, dataWidthOffsetted, bWidth, alignToRight); } return dataWidth; }
protected internal override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string displayText, bool cellIsVisible) { this.DebugOut("Begining Edit, rowNum :" + rowNum.ToString(CultureInfo.InvariantCulture)); Rectangle rc = bounds; this.edit.ReadOnly = (readOnly || this.ReadOnly) || this.DataGridTableStyle.ReadOnly; this.edit.Text = this.GetText(this.GetColumnValueAtRow(source, rowNum)); if (!this.edit.ReadOnly && (displayText != null)) { this.DataGridTableStyle.DataGrid.ColumnStartedEditing(bounds); this.edit.IsInEditOrNavigateMode = false; this.edit.Text = displayText; } if (cellIsVisible) { bounds.Offset(this.xMargin, 2 * this.yMargin); bounds.Width -= this.xMargin; bounds.Height -= 2 * this.yMargin; this.DebugOut("edit bounds: " + bounds.ToString()); this.edit.Bounds = bounds; this.edit.Visible = true; this.edit.TextAlign = this.Alignment; } else { this.edit.Bounds = Rectangle.Empty; } this.edit.RightToLeft = this.DataGridTableStyle.DataGrid.RightToLeft; this.edit.FocusInternal(); this.editRow = rowNum; if (!this.edit.ReadOnly) { this.oldValue = this.edit.Text; } if (displayText == null) { this.edit.SelectAll(); } else { int length = this.edit.Text.Length; this.edit.Select(length, 0); } if (this.edit.Visible) { this.DataGridTableStyle.DataGrid.Invalidate(rc); } }
protected override void OnPaint(PaintEventArgs pe) { Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose, "PropertyGridView:OnPaint"); Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "On paint called. Rect=" + pe.ClipRectangle.ToString()); Graphics g = pe.Graphics; int yPos = 0; int startRow = 0; int endRow = visibleRows - 1; Rectangle clipRect = pe.ClipRectangle; // give ourselves a little breathing room to account for lines, etc., as well // as the entries themselves. // clipRect.Inflate(0,2); try { Size sizeWindow = this.Size; // figure out what rows we're painting Point posStart = FindPosition(clipRect.X, clipRect.Y); Point posEnd = FindPosition(clipRect.X, clipRect.Y + clipRect.Height); if (posStart != InvalidPosition) { startRow = Math.Max(0,posStart.Y); } if (posEnd != InvalidPosition) { endRow = posEnd.Y; } int cPropsVisible = Math.Min(totalProps - GetScrollOffset(),1+visibleRows); #if DEBUG GridEntry debugIPEStart = GetGridEntryFromRow(startRow); GridEntry debugIPEEnd = GetGridEntryFromRow(endRow); string startName = debugIPEStart == null ? null : debugIPEStart.PropertyLabel; if (startName == null) { startName = "(null)"; } string endName = debugIPEEnd == null ? null : debugIPEEnd.PropertyLabel; if (endName == null) { endName = "(null)"; } #endif SetFlag(FlagNeedsRefresh, false); //SetConstants(); Size size = this.GetOurSize(); Point loc = this.ptOurLocation; if (GetGridEntryFromRow(cPropsVisible-1) == null) { cPropsVisible--; } // if we actually have some properties, then start drawing the grid // if (totalProps > 0) { // draw splitter cPropsVisible = Math.Min(cPropsVisible, endRow+1); Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing splitter"); Pen splitterPen = new Pen(ownerGrid.LineColor, GetSplitterWidth()); splitterPen.DashStyle = DashStyle.Solid; g.DrawLine(splitterPen, labelWidth,loc.Y,labelWidth, (cPropsVisible)*(RowHeight+1)+loc.Y); splitterPen.Dispose(); // draw lines. Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Drawing lines"); Pen linePen = new Pen(g.GetNearestColor(ownerGrid.LineColor)); int cHeightCurRow = 0; int cLineEnd = loc.X + size.Width; int cLineStart = loc.X; // draw values. int totalWidth = GetTotalWidth() + 1; //g.TextColor = ownerGrid.TextColor; // draw labels. set clip rect. for (int i = startRow; i < cPropsVisible; i++) { try { // draw the line cHeightCurRow = (i)*(RowHeight+1) + loc.Y; g.DrawLine(linePen, cLineStart,cHeightCurRow,cLineEnd,cHeightCurRow); // draw the value DrawValueEntry(g,i, ref clipRect); // draw the label Rectangle rect = GetRectangle(i,ROWLABEL); yPos = rect.Y + rect.Height; DrawLabel(g,i, rect, (i==selectedRow),false, ref clipRect); if (i == selectedRow) { Edit.Invalidate(); } } catch { Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Exception thrown during painting property " + GetGridEntryFromRow(i).PropertyLabel); } } // draw the bottom line cHeightCurRow = (cPropsVisible)*(RowHeight+1) + loc.Y; g.DrawLine(linePen, cLineStart,cHeightCurRow,cLineEnd,cHeightCurRow); linePen.Dispose(); } // fill anything left with window if (yPos < Size.Height) { yPos++; Rectangle clearRect = new Rectangle(1, yPos, Size.Width - 2, Size.Height - yPos - 1); Debug.WriteLineIf(GridViewDebugPaint.TraceVerbose, "Filling remaining area rect=" + clearRect.ToString()); g.FillRectangle(backgroundBrush, clearRect); } // draw outside border using (Pen borderPen = new Pen(ownerGrid.ViewBorderColor, 1)) { g.DrawRectangle(borderPen, 0, 0, sizeWindow.Width - 1, sizeWindow.Height - 1); } fontBold = null; } catch { Debug.Fail("Caught exception in OnPaint"); // Do nothing. } finally { ClearCachedFontInfo(); } }
private void SelectRectangle() { WindowState = FormWindowState.Minimized; try { Thread.Sleep(250); Rectangle rect; if (RegionCaptureTasks.GetRectangleRegion(out rect, RegionCaptureOptions)) { selectedRectangle = rect; lblSelectedRectangle.Text = selectedRectangle.ToString(); } } finally { this.ForceActivate(); } }
private void SelectRectangle() { WindowState = FormWindowState.Minimized; try { Thread.Sleep(250); Rectangle rect; if (SurfaceForm.SelectRegion(out rect)) { selectedRectangle = rect; lblSelectedRectangle.Text = selectedRectangle.ToString(); } } finally { this.ForceActivate(); } }
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, LinearGradientMode linearGradientMode) { //validate the LinearGradientMode enum //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(linearGradientMode, unchecked((int)linearGradientMode), (int)LinearGradientMode.Horizontal, (int)LinearGradientMode.BackwardDiagonal)) { throw new InvalidEnumArgumentException("linearGradientMode", unchecked((int)linearGradientMode), typeof(LinearGradientMode)); } //validate the rect if (rect.Width == 0 || rect.Height == 0) { throw new ArgumentException(SR.GetString(SR.GdiplusInvalidRectangle, rect.ToString())); } IntPtr brush = IntPtr.Zero; GPRECT gpRect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectI(ref gpRect, color1.ToArgb(), color2.ToArgb(), unchecked((int) linearGradientMode), (int)WrapMode.Tile, out brush); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeBrushInternal(brush); }
/// <summary> /// Draw Sub Item (Cell) at location specified /// </summary> /// <param name="graphicsSubItem"></param> /// <param name="rectSubItem"></param> /// <param name="item"></param> /// <param name="subItem"></param> /// <param name="nColumn"></param> public virtual void DrawSubItem( Graphics graphicsSubItem, Rectangle rectSubItem, GLItem item, GLSubItem subItem, int nColumn ) { DW("DrawSubItem"); // precheck to make sure this is big enough for the things we want to do inside it Rectangle subControlRect = new Rectangle( rectSubItem.X, rectSubItem.Y, rectSubItem.Width, rectSubItem.Height ); if ( ( subItem.Control != null ) && (!subItem.ForceText ) ) { // custom embedded control here Control control = subItem.Control; if ( control.Parent != this ) // *** CRUCIAL *** this makes sure the parent is the list control control.Parent = this; // Rectangle subrc = new Rectangle( // subControlRect.X+this.CellPaddingSize, // subControlRect.Y+this.CellPaddingSize, // subControlRect.Width-this.CellPaddingSize*2, // subControlRect.Height-this.CellPaddingSize*2 ); Rectangle subrc = new Rectangle( subControlRect.X, subControlRect.Y+1, subControlRect.Width, subControlRect.Height-1 ); Type tp = control.GetType(); PropertyInfo pi = control.GetType().GetProperty( "PreferredHeight" ); if ( pi != null ) { int PreferredHeight = (int)pi.GetValue( control, null ); if ( ( (PreferredHeight + this.CellPaddingSize*2)> this.ItemHeight ) && AutoHeight ) this.ItemHeight = PreferredHeight + this.CellPaddingSize*2; subrc.Y = subControlRect.Y + ((subControlRect.Height - PreferredHeight)/2); } NewLiveControls.Add( control ); // put it in the new list, remove from old list if ( LiveControls.Contains( control ) ) // make sure its in the old list first { LiveControls.Remove( control ); // remove it from list so it doesn't get put down } if ( control.Bounds.ToString() != subrc.ToString() ) control.Bounds = subrc; // this will force an invalidation if ( control.Visible != true ) control.Visible = true; } else // not control based { // if the sub item color is not the same as the back color fo the control, AND the item is not selected, then color this sub item background if ( ( subItem.BackColor.ToArgb() != this.BackColor.ToArgb() ) && (!item.Selected) && ( subItem.BackColor != Color.White ) ) { SolidBrush bbrush = new SolidBrush( subItem.BackColor ); graphicsSubItem.FillRectangle( bbrush, rectSubItem ); bbrush.Dispose(); } // do we need checkboxes in this column or not? if ( this.Columns[ nColumn ].CheckBoxes ) rectSubItem = DrawCheckBox( graphicsSubItem, rectSubItem, subItem.Checked ); // if there is an image, this routine will RETURN with exactly the space left for everything else after the image is drawn (or not drawn due to lack of space) if ( (subItem.ImageIndex > -1) && (ImageList != null) && (subItem.ImageIndex < this.ImageList.Images.Count) ) rectSubItem = DrawCellGraphic( graphicsSubItem, rectSubItem, this.ImageList.Images[ subItem.ImageIndex ], subItem.ImageAlignment ); // deal with text color in a box on whether it is selected or not Color textColor; if ( item.Selected && this.Selectable ) textColor = this.SelectedTextColor; else { textColor = this.ForeColor; if ( item.ForeColor.ToArgb() != this.ForeColor.ToArgb() ) textColor = item.ForeColor; else if ( subItem.ForeColor.ToArgb() != this.ForeColor.ToArgb() ) textColor = subItem.ForeColor; } DrawCellText( graphicsSubItem, rectSubItem, subItem.Text, Columns[nColumn].TextAlignment, textColor, item.Selected, ItemWordWrap ); subItem.LastCellRect = rectSubItem; // important to ONLY catch the area where the text is drawn } }
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, float angle, bool isAngleScaleable) { IntPtr brush = IntPtr.Zero; //validate the rect if (rect.Width == 0 || rect.Height == 0) { throw new ArgumentException(SR.GetString(SR.GdiplusInvalidRectangle, rect.ToString())); } GPRECT gprect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectWithAngleI(ref gprect, color1.ToArgb(), color2.ToArgb(), angle, isAngleScaleable, (int)WrapMode.Tile, out brush); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeBrushInternal(brush); }
/// <summary> /// Make a full-size thumbnail of the captured window on a new topmost form, and capture /// this new form with a black and then white background. Then compute the transparency by /// difference between the black and white versions. /// This method has these advantages: /// - the full form is captured even if it is obscured on the Windows desktop /// - there is no problem with unpredictable Z-order anymore (the background and /// the window to capture are drawn on the same window) /// </summary> /// <param name="handle">handle of the window to capture</param> /// <param name="windowRect">the bounds of the window</param> /// <param name="redBGImage">the window captured with a red background</param> /// <param name="captureRedBGImage">whether to do the capture of the window with a red background</param> /// <returns>the captured window image</returns> private static Image CaptureWindowWithDWM(IntPtr handle, Rectangle windowRect, out Bitmap redBGImage, Color backColor) { Image windowImage = null; redBGImage = null; if (backColor != Color.White) { backColor = Color.FromArgb(255, backColor.R, backColor.G, backColor.B); } using (Form form = new Form()) { form.StartPosition = FormStartPosition.Manual; form.FormBorderStyle = FormBorderStyle.None; form.ShowInTaskbar = false; form.BackColor = backColor; form.TopMost = true; form.Bounds = CaptureHelpers.GetWindowRectangle(handle, false); IntPtr thumb; NativeMethods.DwmRegisterThumbnail(form.Handle, handle, out thumb); SIZE size; NativeMethods.DwmQueryThumbnailSourceSize(thumb, out size); #if DEBUG DebugHelper.WriteLine("Rectangle Size: " + windowRect.ToString()); DebugHelper.WriteLine("Window Size: " + size.ToString()); #endif if (size.Width <= 0 || size.Height <= 0) { return null; } DWM_THUMBNAIL_PROPERTIES props = new DWM_THUMBNAIL_PROPERTIES(); props.dwFlags = NativeMethods.DWM_TNP_VISIBLE | NativeMethods.DWM_TNP_RECTDESTINATION | NativeMethods.DWM_TNP_OPACITY; props.fVisible = true; props.opacity = (byte)255; props.rcDestination = new RECT(0, 0, size.Width, size.Height); NativeMethods.DwmUpdateThumbnailProperties(thumb, ref props); form.Show(); System.Threading.Thread.Sleep(250); if (form.BackColor != Color.White) { // no need for transparency; user has requested custom background color NativeMethods.ActivateWindowRepeat(form.Handle, 250); windowImage = Screenshot.CaptureRectangleNative(windowRect) as Bitmap; } else if (form.BackColor == Color.White) { // transparent capture NativeMethods.ActivateWindowRepeat(handle, 250); Bitmap whiteBGImage = Screenshot.CaptureRectangleNative(windowRect) as Bitmap; form.BackColor = Color.Black; form.Refresh(); NativeMethods.ActivateWindowRepeat(handle, 250); Bitmap blackBGImage = Screenshot.CaptureRectangleNative(windowRect) as Bitmap; // Capture rounded corners with except for Windows 8 if (ZAppHelper.IsWindows8()) { form.BackColor = Color.Red; form.Refresh(); NativeMethods.ActivateWindowRepeat(handle, 250); redBGImage = Screenshot.CaptureRectangleNative(windowRect) as Bitmap; } form.BackColor = Color.White; form.Refresh(); NativeMethods.ActivateWindowRepeat(handle, 250); Bitmap whiteBGImage2 = Screenshot.CaptureRectangleNative(windowRect) as Bitmap; // Don't do transparency calculation if an animated picture is detected if (whiteBGImage.AreBitmapsEqual(whiteBGImage2)) { windowImage = HelpersLib.GraphicsHelper.Core.ComputeOriginal(whiteBGImage, blackBGImage); } else { DebugHelper.WriteLine("Detected animated image => cannot compute transparency"); form.Close(); Application.DoEvents(); Image result = new Bitmap(whiteBGImage.Width, whiteBGImage.Height, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(result)) { // Redraw the image on a black background to avoid transparent pixels artifacts g.Clear(Color.Black); g.DrawImage(whiteBGImage, 0, 0); } windowImage = result; } blackBGImage.Dispose(); whiteBGImage.Dispose(); whiteBGImage2.Dispose(); } NativeMethods.DwmUnregisterThumbnail(thumb); } return windowImage; }
/// <summary> /// This method is responsible for drawing the circle to the screen /// using the coordinates and dimensions set by the other methods. /// </summary> private void updateShapes(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Rectangle rect = new Rectangle(boxX, boxY, boxWidth, boxHeight); Console.WriteLine(rect.ToString()); //g.DrawRectangle(Pens.Black, rect); //g.DrawEllipse(Pens.Black, rect); SolidBrush sb = new SolidBrush(circleColor); g.FillEllipse(sb, rect); }
public LinearGradientBrush(System.Drawing.Rectangle rect, Color color1, Color color2, float angle, bool isAngleScaleable) { IntPtr zero = IntPtr.Zero; if ((rect.Width == 0) || (rect.Height == 0)) { throw new ArgumentException(System.Drawing.SR.GetString("GdiplusInvalidRectangle", new object[] { rect.ToString() })); } GPRECT gprect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectWithAngleI(ref gprect, color1.ToArgb(), color2.ToArgb(), angle, isAngleScaleable, 0, out zero); if (status != 0) { throw SafeNativeMethods.Gdip.StatusException(status); } base.SetNativeBrushInternal(zero); }
/// <summary> /// Crops the capture to the specified rectangle (with Bitmap coordinates!) /// </summary> /// <param name="cropRectangle">Rectangle with bitmap coordinates</param> public bool Crop(Rectangle cropRectangle) { LOG.Debug("Cropping to: " + cropRectangle.ToString()); if (ImageHelper.Crop(ref _image, ref cropRectangle)) { _location = cropRectangle.Location; // Change mouse location according to the cropRegtangle (including screenbounds) offset MoveMouseLocation(-cropRectangle.Location.X, -cropRectangle.Location.Y); // Move all the elements // TODO: Enable when the elements are usable again. // MoveElements(-cropRectangle.Location.X, -cropRectangle.Location.Y); // Remove invisible elements List <ICaptureElement> newElements = new List<ICaptureElement>(); foreach(ICaptureElement captureElement in _elements) { if (captureElement.Bounds.IntersectsWith(cropRectangle)) { newElements.Add(captureElement); } } _elements = newElements; return true; } return false; }
public static void DebugRectangle (Graphics graphics,Rectangle rectangle) { if (graphics == null) { throw new ArgumentNullException("graphics"); } graphics.DrawRectangle (Pens.LightGray,rectangle); string s = String.Format(CultureInfo.InvariantCulture, // "Left: {0} , Top: {1}",rectangle.Left.ToString(CultureInfo.CurrentCulture),rectangle.Top.ToString(CultureInfo.CurrentCulture)); "Sectionrectangle : {0} ",rectangle.ToString()); Font f = new Font(FontFamily.GenericSerif,10); graphics.DrawString(s, f, Brushes.Red, rectangle.Left,rectangle.Top - f.Height/2); f.Dispose(); }
public LinearGradientBrush(System.Drawing.Rectangle rect, Color color1, Color color2, LinearGradientMode linearGradientMode) { if (!System.Drawing.ClientUtils.IsEnumValid(linearGradientMode, (int)linearGradientMode, 0, 3)) { throw new InvalidEnumArgumentException("linearGradientMode", (int)linearGradientMode, typeof(LinearGradientMode)); } if ((rect.Width == 0) || (rect.Height == 0)) { throw new ArgumentException(System.Drawing.SR.GetString("GdiplusInvalidRectangle", new object[] { rect.ToString() })); } IntPtr zero = IntPtr.Zero; GPRECT gprect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCreateLineBrushFromRectI(ref gprect, color1.ToArgb(), color2.ToArgb(), (int)linearGradientMode, 0, out zero); if (status != 0) { throw SafeNativeMethods.Gdip.StatusException(status); } base.SetNativeBrushInternal(zero); }
public void Init(Output output, GDI.Rectangle srcRect) { logger.Debug("DesktopDuplicator::Init(...) " + srcRect.ToString()); try { var descr = output.Description; RawRectangle screenRect = descr.DesktopBounds; int width = screenRect.Right - screenRect.Left; int height = screenRect.Bottom - screenRect.Top; SetupRegions(screenRect, srcRect); if (descr.DeviceName == "\\\\.\\DISPLAY1") { drawRect = new Rectangle { X = 1920, Y = 0, Width = width, Height = height, }; } else if (descr.DeviceName == "\\\\.\\DISPLAY2") { drawRect = new Rectangle { X = 0, Y = 0, Width = width, Height = height, }; } screenTexture = new Texture2D(device, new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, }); using (SharpDX.Direct2D1.Factory1 factory2D1 = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.MultiThreaded)) { using (var surf = screenTexture.QueryInterface <Surface>()) { var pixelFormat = new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied); var renderTargetProps = new Direct2D.RenderTargetProperties(pixelFormat); screenTarget = new Direct2D.RenderTarget(factory2D1, surf, renderTargetProps); } } using (var output1 = output.QueryInterface <Output1>()) { // Duplicate the output deskDupl = output1.DuplicateOutput(device); } } catch (Exception ex) { logger.Error(ex); Close(); throw; } deviceReady = true; }
/// <devdoc> /// Called by the dataGrid when it needs the caption /// to repaint. /// </devdoc> internal void Paint(Graphics g, Rectangle bounds, bool alignRight) { Size textSize = new Size((int) g.MeasureString(text, this.Font).Width + 2, this.Font.Height + 2); downButtonRect = GetDetailsButtonRect(bounds, alignRight); int downButtonWidth = GetDetailsButtonWidth(); backButtonRect = GetBackButtonRect(bounds, alignRight, downButtonWidth); int backButtonArea = backButtonVisible ? backButtonRect.Width + xOffset + buttonToText : 0; int downButtonArea = downButtonVisible && !dataGrid.ParentRowsIsEmpty() ? downButtonWidth + xOffset + buttonToText : 0; int textWidthLeft = bounds.Width - xOffset - backButtonArea - downButtonArea; textRect = new Rectangle( bounds.X, bounds.Y + yOffset, Math.Min(textWidthLeft, 2 * textPadding + textSize.Width), 2 * textPadding + textSize.Height); // align the caption text box, downButton, and backButton // if the RigthToLeft property is set to true if (alignRight) { textRect.X = bounds.Right - textRect.Width; backButtonRect.X = bounds.X + xOffset * 4 + downButtonWidth; downButtonRect.X = bounds.X + xOffset * 2; } Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "text size = " + textSize.ToString()); Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "downButtonWidth = " + downButtonWidth.ToString(CultureInfo.InvariantCulture)); Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "textWidthLeft = " + textWidthLeft.ToString(CultureInfo.InvariantCulture)); Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "backButtonRect " + backButtonRect.ToString()); Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "textRect " + textRect.ToString()); Debug.WriteLineIf(CompModSwitches.DGCaptionPaint.TraceVerbose, "downButtonRect " + downButtonRect.ToString()); // we should use the code that is commented out // with today's code, there are pixels on the backButtonRect and the downButtonRect // that are getting painted twice // g.FillRectangle(backBrush, bounds); if (backButtonVisible) { PaintBackButton(g, backButtonRect, alignRight); if (backActive) { if (lastMouseLocation == CaptionLocation.BackButton) { backButtonRect.Inflate(1,1); ControlPaint.DrawBorder3D(g, backButtonRect, backPressed ? Border3DStyle.SunkenInner : Border3DStyle.RaisedInner); } } } PaintText(g, textRect, alignRight); if (downButtonVisible && !dataGrid.ParentRowsIsEmpty()) { PaintDownButton(g, downButtonRect); // the rules have changed, yet again. // now: if we show the parent rows and the mouse is // not on top of this icon, then let the icon be depressed. // if the mouse is pressed over the icon, then show the icon pressed // if the mouse is over the icon and not pressed, then show the icon SunkenInner; // if (lastMouseLocation == CaptionLocation.DownButton) { downButtonRect.Inflate(1,1); ControlPaint.DrawBorder3D(g, downButtonRect, downPressed ? Border3DStyle.SunkenInner : Border3DStyle.RaisedInner); } } }
/// <summary> /// Our present hook that will grab a copy of the backbuffer when requested. Note: this supports multi-sampling (anti-aliasing) /// </summary> /// <param name="swapChainPtr"></param> /// <param name="syncInterval"></param> /// <param name="flags"></param> /// <returns>The HRESULT of the original method</returns> int PresentHook(IntPtr swapChainPtr, int syncInterval, SlimDX.DXGI.PresentFlags flags) { try { if (_swapChain == null) { _swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr); } SwapChain swapChain = _swapChain; { CheckAuto(); UpdateFPS(); try { #region Screenshot Request if (this.Request != null) { try { this.DebugMessage("PresentHook: Request Start"); LastRequestTime = DateTime.Now; DateTime startTime = DateTime.Now; using (Texture2D texture = Texture2D.FromSwapChain <SlimDX.Direct3D10.Texture2D>(swapChain, 0)) { #region Determine region to capture System.Drawing.Rectangle regionToCapture = new System.Drawing.Rectangle(0, 0, texture.Description.Width, texture.Description.Height); System.Drawing.Rectangle regionToCaptureDest = new System.Drawing.Rectangle(0, 0, texture.Description.Width, texture.Description.Height); DebugMessage("from " + regionToCapture.ToString() + " to " + regionToCaptureDest.ToString()); //DebugMessage("Flags: "+flags.ToString()); //if (this.Request.RegionToCapture.Width > 0) //{ // regionToCapture = this.Request.RegionToCapture; //} #endregion ////start old //var theTexture = texture; //// If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture //Texture2D textureResolved = null; //if (texture.Description.SampleDescription.Count > 1) //{ // this.DebugMessage("PresentHook: resolving multi-sampled texture"); // // texture is multi-sampled, lets resolve it down to single sample // textureResolved = new Texture2D(texture.Device, new Texture2DDescription() // { // CpuAccessFlags = CpuAccessFlags.None, // Format = texture.Description.Format, // Height = texture.Description.Height, // Usage = ResourceUsage.Default, // Width = texture.Description.Width, // ArraySize = 1, // SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0), // Ensure single sample // BindFlags = BindFlags.None, // MipLevels = 1, // OptionFlags = texture.Description.OptionFlags // }); // // Resolve into textureResolved // texture.Device.ResolveSubresource(texture, 0, textureResolved, 0, texture.Description.Format); // // Make "theTexture" be the resolved texture // theTexture = textureResolved; //} //// Create destination texture //Texture2D textureDest = new Texture2D(texture.Device, new Texture2DDescription() //{ // CpuAccessFlags = CpuAccessFlags.None,// CpuAccessFlags.Write | CpuAccessFlags.Read, // Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm, // Supports BMP/PNG // Height = regionToCapture.Height, // Usage = ResourceUsage.Default,// ResourceUsage.Staging, // Width = regionToCapture.Width, // ArraySize = 1,//texture.Description.ArraySize, // SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0),// texture.Description.SampleDescription, // BindFlags = BindFlags.None, // MipLevels = 1,//texture.Description.MipLevels, // OptionFlags = texture.Description.OptionFlags //}); //// Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index //theTexture.Device.CopySubresourceRegion(theTexture, 0, new ResourceRegion() //{ // Top = regionToCapture.Top, // Bottom = regionToCapture.Bottom, // Left = regionToCapture.Left, // Right = regionToCapture.Right, // Front = 0, // Back = 1 // Must be 1 or only black will be copied //}, textureDest, 0, 0, 0, 0); ////end old var theTexture = texture; DebugMessage(texture.Description.Format.ToString()); // If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture Texture2D textureResolved = null; if (texture.Description.SampleDescription.Count > 1) { this.DebugMessage("PresentHook: resolving multi-sampled texture"); // texture is multi-sampled, lets resolve it down to single sample textureResolved = new Texture2D(texture.Device, new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.None, Format = texture.Description.Format, Height = texture.Description.Height, Usage = ResourceUsage.Default, Width = texture.Description.Width, ArraySize = 1, SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0), // Ensure single sample BindFlags = BindFlags.None, MipLevels = 1, OptionFlags = texture.Description.OptionFlags }); // Resolve into textureResolved texture.Device.ResolveSubresource(texture, 0, textureResolved, 0, texture.Description.Format); // Make "theTexture" be the resolved texture theTexture = textureResolved; } //SlimDX.Direct3D10.Device d2 = new SlimDX.Direct3D10_1.Device1(DriverType.Hardware, SlimDX.Direct3D10.DeviceCreationFlags.None, FeatureLevel.Level_10_1); // Create destination texture if (textureDest == null) { textureDest = new Texture2D(texture.Device, new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.Read, //CpuAccessFlags.Read, Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm, // Supports BMP/PNG Height = regionToCaptureDest.Height, Usage = ResourceUsage.Staging, // ResourceUsage.Default, Width = regionToCaptureDest.Width, ArraySize = 1, //texture.Description.ArraySize, SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0), // texture.Description.SampleDescription, BindFlags = BindFlags.None, MipLevels = 1, //texture.Description.MipLevels, OptionFlags = texture.Description.OptionFlags //| ResourceOptionFlags.GdiCompatible }); } Texture2D theTexture2 = new Texture2D(texture.Device, new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.None, Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,//texture.Description.Format, Height = regionToCaptureDest.Height, Usage = ResourceUsage.Default, Width = regionToCaptureDest.Width, ArraySize = 1, SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0), // Ensure single sample BindFlags = BindFlags.None, MipLevels = 1, OptionFlags = texture.Description.OptionFlags //| ResourceOptionFlags.GdiCompatible }); Result r = SlimDX.Direct3D10.Resource.LoadTextureFromTexture(theTexture, theTexture2, new TextureLoadInformation() { SourceRegion = new ResourceRegion() { Top = regionToCapture.Top, Bottom = regionToCapture.Bottom, Left = regionToCapture.Left, Right = regionToCapture.Right, Front = 0, Back = 1 // Must be 1 or only black will be copied }, DestinationRegion = new ResourceRegion() { Top = regionToCaptureDest.Top, Bottom = regionToCaptureDest.Bottom, Left = regionToCaptureDest.Left, Right = regionToCaptureDest.Right, Front = 0, Back = 1 // Must be 1 or only black will be copied }, ElementCount = 1, Filter = FilterFlags.Linear, FirstDestinationElement = 0, FirstDestinationMip = 0, FirstSourceElement = 0, FirstSourceMip = 0, MipCount = 1, MipFilter = FilterFlags.Linear }); DebugMessage("Result: " + r.ToString()); // Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index theTexture.Device.CopySubresourceRegion(theTexture2, 0, new ResourceRegion() { Top = regionToCaptureDest.Top, Bottom = regionToCaptureDest.Bottom, Left = regionToCaptureDest.Left, Right = regionToCaptureDest.Right, Front = 0, Back = 1 // Must be 1 or only black will be copied }, textureDest, 0, 0, 0, 0); theTexture.Device.CopyResource(theTexture, textureDest); #region copy f*****g texture to f*****g bitmap and save it DataRectangle dr = textureDest.Map(0, MapMode.Read, SlimDX.Direct3D10.MapFlags.None); IntPtr data = dr.Data.DataPointer; int width = textureDest.Description.Width; int height = textureDest.Description.Height; //WriteableBitmap wbmap = new WriteableBitmap(width, height, 300, 300, PixelFormats.Bgra32, null); //CopyMemory(wbmap.BackBuffer, data, (uint)(width * height * 4)); if (bitmap == null) { bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb); dd = new byte[width * height * 4]; } Marshal.Copy(data, dd, 0, dd.Length); textureDest.Unmap(0); for (int i = 0; i < dd.Length; i += 4) { byte tmp = dd[i]; dd[i] = dd[i + 2]; dd[i + 2] = tmp; } BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat); Marshal.Copy(dd, 0, bd.Scan0, dd.Length); //CopyMemory(bd.Scan0, data, (uint)(width * height * 4)); bitmap.UnlockBits(bd); //textureDest.Unmap(0); //FileStream stream = new FileStream(@"c:\temp\new.png", FileMode.Create); //PngBitmapEncoder encoder = new PngBitmapEncoder(); ////TextBlock myTextBlock = new TextBlock(); ////myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString(); //encoder.Interlace = PngInterlaceOption.On; //encoder.Frames.Add(BitmapFrame.Create(wbmap)); //encoder.Save(stream); SaveFile(); #endregion //Texture2D.ToFile(textureDest, ImageFileFormat.Png, @"c:\temp\dx10.png"); //Texture2D.ToFile(textureDest, GetImageFileFormat(this.Request.Format), this.Request.FileName); // Make sure we free up the resolved texture if it was created if (textureResolved != null) { textureResolved.Dispose(); textureResolved = null; } } this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString()); this.DebugMessage("PresentHook: Request End"); } finally { // Prevent the request from being processed a second time this.Request = null; } } #endregion #region Draw the f*****g overlay using (Texture2D texture = Texture2D.FromSwapChain <SlimDX.Direct3D10.Texture2D>(swapChain, 0)) { DrawOverlay(texture); //DrawSprite(texture.Device); } #endregion #region Example: Draw overlay (after screenshot so we don't capture overlay as well) //if (this.ShowOverlay) //{ // using (Texture2D texture = Texture2D.FromSwapChain<SlimDX.Direct3D10.Texture2D>(swapChain, 0)) // { // if (_lastFrame != null) // { // FontDescription fd = new SlimDX.Direct3D10.FontDescription() // { // Height = 16, // FaceName = "Times New Roman", // IsItalic = false, // Width = 0, // MipLevels = 1, // CharacterSet = SlimDX.Direct3D10.FontCharacterSet.Default, // Precision = SlimDX.Direct3D10.FontPrecision.Default, // Quality = SlimDX.Direct3D10.FontQuality.Antialiased, // PitchAndFamily = FontPitchAndFamily.Default | FontPitchAndFamily.DontCare // }; // using (Font font = new Font(texture.Device, fd)) // { // DrawText(font, new Vector2(100, 100), String.Format("{0}", DateTime.Now), new Color4(System.Drawing.Color.Red.R, System.Drawing.Color.Red.G, System.Drawing.Color.Red.B, System.Drawing.Color.Red.A)); // } // } // _lastFrame = DateTime.Now; // } //} #endregion } catch (Exception e) { // If there is an error we do not want to crash the hooked application, so swallow the exception this.DebugMessage(e.ToString()); } // As always we need to call the original method, note that EasyHook has already repatched the original method // so calling it here will not cause an endless recursion to this function return(swapChain.Present(syncInterval, flags).Code); } } catch (Exception ex) { DebugMessage(ex.ToString()); return(System.Runtime.InteropServices.Marshal.GetHRForException(ex)); } }
public Bitmap Clone(Rectangle rect, PixelFormat format) { if ((rect.Width == 0) || (rect.Height == 0)) { throw new ArgumentException(System.Drawing.SR.GetString("GdiplusInvalidRectangle", new object[] { rect.ToString() })); } IntPtr zero = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneBitmapAreaI(rect.X, rect.Y, rect.Width, rect.Height, (int)format, new HandleRef(this, base.nativeImage), out zero); if ((status != 0) || (zero == IntPtr.Zero)) { throw SafeNativeMethods.Gdip.StatusException(status); } return(FromGDIplus(zero)); }
/// <summary> /// Provides a default implementation for performing dst = F(dst, src) or F(src) over some rectangle /// of interest. May be slightly faster than calling the other multi-parameter Apply method, as less /// variables are used in the implementation, thus inducing less register pressure. /// </summary> /// <param name="dst">The Surface to write pixels to, and from which pixels are read and used as the lhs parameter for calling the method <b>ColorBgra Apply(ColorBgra, ColorBgra)</b>.</param> /// <param name="dstOffset">The pixel offset that defines the upper-left of the rectangle-of-interest for the dst Surface.</param> /// <param name="src">The Surface to read pixels from for the rhs parameter given to the method <b>ColorBgra Apply(ColorBgra, ColorBgra)</b>b>.</param></param> /// <param name="srcOffset">The pixel offset that defines the upper-left of the rectangle-of-interest for the src Surface.</param> /// <param name="roiSize">The size of the rectangles-of-interest for all Surfaces.</param> public void ApplyBase(Surface dst, Point dstOffset, Surface src, Point srcOffset, Size roiSize) { // Create bounding rectangles for each Surface Rectangle dstRect = new Rectangle(dstOffset, roiSize); if (dstRect.Width == 0 || dstRect.Height == 0) { return; } Rectangle srcRect = new Rectangle(srcOffset, roiSize); if (srcRect.Width == 0 || srcRect.Height == 0) { return; } // Clip those rectangles to those Surface's bounding rectangles Rectangle dstClip = Rectangle.Intersect(dstRect, dst.Bounds); Rectangle srcClip = Rectangle.Intersect(srcRect, src.Bounds); // If any of those Rectangles actually got clipped, then throw an exception if (dstRect != dstClip) { throw new ArgumentOutOfRangeException ( "roiSize", "Destination roi out of bounds" + ", dst.Size=" + dst.Size.ToString() + ", dst.Bounds=" + dst.Bounds.ToString() + ", dstOffset=" + dstOffset.ToString() + ", src.Size=" + src.Size.ToString() + ", srcOffset=" + srcOffset.ToString() + ", roiSize=" + roiSize.ToString() + ", dstRect=" + dstRect.ToString() + ", dstClip=" + dstClip.ToString() + ", srcRect=" + srcRect.ToString() + ", srcClip=" + srcClip.ToString() ); } if (srcRect != srcClip) { throw new ArgumentOutOfRangeException("roiSize", "Source roi out of bounds"); } // Cache the width and height properties int width = roiSize.Width; int height = roiSize.Height; // Do the work. unsafe { for (int row = 0; row < roiSize.Height; ++row) { ColorBgra *dstPtr = dst.GetPointAddress(dstOffset.X, dstOffset.Y + row); ColorBgra *srcPtr = src.GetPointAddress(srcOffset.X, srcOffset.Y + row); Apply(dstPtr, srcPtr, width); } } }
public Bitmap Clone(Rectangle rect, PixelFormat format) { //validate the rect if (rect.Width == 0 || rect.Height == 0) { throw new ArgumentException(SR.GetString(SR.GdiplusInvalidRectangle, rect.ToString())); } IntPtr dstHandle = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneBitmapAreaI( rect.X, rect.Y, rect.Width, rect.Height, unchecked((int) format), new HandleRef(this, nativeImage), out dstHandle); if (status != SafeNativeMethods.Gdip.Ok || dstHandle == IntPtr.Zero) throw SafeNativeMethods.Gdip.StatusException(status); return Bitmap.FromGDIplus(dstHandle); }