Скриншот гаджетов рабочего стола windows 7 - C#

Узнай цену своей работы

Формулировка задачи:

Доброй ночи. Спешу сообщить - да, гуглил. Естественно - уйма всего нагуглилось, но:

Во первых

, вот "почти" рабочий код:
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace ScreenShot
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  18. private void button1_Click(object sender, EventArgs e)
  19. {
  20. Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
  21. Graphics graphics = Graphics.FromImage(printscreen as Image);
  22. graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
  23. printscreen.Save(@"screenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
  24. }
  25. }
  26. }
К этому коду есть 2 основных нарекания: 1) Течет память. Я новичок совсем, нагуглил, что нужно "обернуть" вот это и это:
Листинг программы
  1. Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
  2. Graphics graphics = Graphics.FromImage(printscreen as Image);
в using(), пока разбираюсь "как это правильно делается"; 2) На получаемом скрине нет тех самых гаджетов, потому что оверлей, судя по всему.

Во вторых

, мне бы подошло и "костыльное" решение, через принудительное отключение ускорения DirectDraw в системе, но тут "засада" - почему-то при открытии “dxdiag” as Administrator на вкладке Display у меня нет кнопок для включения/отключения режимов! (( Как это выглядит у других: ссылка на сторонний сайт Как это выглядит у меня: (приложил скриншот dxdiag.png)

И наконец, в третьих

: абсолютно во всех ветках (включая стековерфлоу) как только речь заходит об скриншоте оверлея ссылаются на одну и ту же страницу: Чудо а не рецепт, панацея просто, но к моему глубочайшему сожалению я мало того, что слаб в шарпе - я еще и с английским "на Вы". Поясните, пожалуйста, "на пальцах", пошагово, как с этим работать, так например, с самого начала: 1) говорится, что будет использоваться SlimDX и дается ссылка на скачивание - скачал SlimDX Runtime .NET 4.0 x64 (January 2012).msi, установил; 2)
"The download already includes the EasyHook binaries, but if you want to download them yourself you can find them at CodePlex here."
Вот тут не понял: куда оно "уже включено"? На всякий случай скачал архив, в нем 2 папки, подозреваю, нужно NetFX4.0 подложить к проекту: как/куда/как "прописать" ? Далее идет совершенно непонятный код, в котором по названиям вызываемых методов даже примерно не понять - в какой строке делается этот самый скриншот, куда и в каком виде он "кладется", и соответственно - не ясно как вызывать/как сохранять... Вот еще статья с того же источника: Еще одна статья на ту же тему, тут не многим легче, если "слепо" скопировать код в студию:
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Drawing;
  5. using System.Runtime.InteropServices;
  6. namespace Spazzarama.ScreenCapture
  7. {
  8. public static class Direct3DCapture
  9. {
  10. private static SlimDX.Direct3D9.Direct3D _direct3D9 = new SlimDX.Direct3D9.Direct3D();
  11. private static Dictionary<IntPtr, SlimDX.Direct3D9.Device> _direct3DDeviceCache = new Dictionary<IntPtr, SlimDX.Direct3D9.Device>();
  12. /// <summary>
  13. /// Capture the entire client area of a window
  14. /// </summary>
  15. /// <param name="hWnd"></param>
  16. /// <returns></returns>
  17. public static Bitmap CaptureWindow(IntPtr hWnd)
  18. {
  19. return CaptureRegionDirect3D(hWnd, NativeMethods.GetAbsoluteClientRect(hWnd));
  20. }
  21. /// <summary>
  22. /// Capture a region of the screen using Direct3D
  23. /// </summary>
  24. /// <param name="handle">The handle of a window</param>
  25. /// <param name="region">The region to capture (in screen coordinates)</param>
  26. /// <returns>A bitmap containing the captured region, this should be disposed of appropriately when finished with it</returns>
  27. public static Bitmap CaptureRegionDirect3D(IntPtr handle, Rectangle region)
  28. {
  29. IntPtr hWnd = handle;
  30. Bitmap bitmap = null;
  31. // We are only supporting the primary display adapter for Direct3D mode
  32. SlimDX.Direct3D9.AdapterInformation adapterInfo = _direct3D9.Adapters.DefaultAdapter;
  33. SlimDX.Direct3D9.Device device;
  34. #region Get Direct3D Device
  35. // Retrieve the existing Direct3D device if we already created one for the given handle
  36. if (_direct3DDeviceCache.ContainsKey(hWnd))
  37. {
  38. device = _direct3DDeviceCache[hWnd];
  39. }
  40. // We need to create a new device
  41. else
  42. {
  43. // Setup the device creation parameters
  44. SlimDX.Direct3D9.PresentParameters parameters = new SlimDX.Direct3D9.PresentParameters();
  45. parameters.BackBufferFormat = adapterInfo.CurrentDisplayMode.Format;
  46. Rectangle clientRect = NativeMethods.GetAbsoluteClientRect(hWnd);
  47. parameters.BackBufferHeight = clientRect.Height;
  48. parameters.BackBufferWidth = clientRect.Width;
  49. parameters.Multisample = SlimDX.Direct3D9.MultisampleType.None;
  50. parameters.SwapEffect = SlimDX.Direct3D9.SwapEffect.Discard;
  51. parameters.DeviceWindowHandle = hWnd;
  52. parameters.PresentationInterval = SlimDX.Direct3D9.PresentInterval.Default;
  53. parameters.FullScreenRefreshRateInHertz = 0;
  54. // Create the Direct3D device
  55. device = new SlimDX.Direct3D9.Device(_direct3D9, adapterInfo.Adapter, SlimDX.Direct3D9.DeviceType.Hardware, hWnd, SlimDX.Direct3D9.CreateFlags.SoftwareVertexProcessing, parameters);
  56. _direct3DDeviceCache.Add(hWnd, device);
  57. }
  58. #endregion
  59. // Capture the screen and copy the region into a Bitmap
  60. using (SlimDX.Direct3D9.Surface surface = SlimDX.Direct3D9.Surface.CreateOffscreenPlain(device, adapterInfo.CurrentDisplayMode.Width, adapterInfo.CurrentDisplayMode.Height, SlimDX.Direct3D9.Format.A8R8G8B8, SlimDX.Direct3D9.Pool.SystemMemory))
  61. {
  62. device.GetFrontBufferData(0, surface);
  63. // Update: thanks digitalutopia1 for pointing out that SlimDX have fixed a bug
  64. // where they previously expected a RECT type structure for their Rectangle
  65. bitmap = new Bitmap(SlimDX.Direct3D9.Surface.ToStream(surface, SlimDX.Direct3D9.ImageFileFormat.Bmp, new Rectangle(region.Left, region.Top, region.Width, region.Height)));
  66. // Previous SlimDX bug workaround: new Rectangle(region.Left, region.Top, region.Right, region.Bottom)));
  67. }
  68. return bitmap;
  69. }
  70. }
  71. #region Native Win32 Interop
  72. /// <summary>
  73. /// The RECT structure defines the coordinates of the upper-left and lower-right corners of a rectangle.
  74. /// </summary>
  75. [Serializable, StructLayout(LayoutKind.Sequential)]
  76. internal struct RECT
  77. {
  78. public int Left;
  79. public int Top;
  80. public int Right;
  81. public int Bottom;
  82. public RECT(int left, int top, int right, int bottom)
  83. {
  84. this.Left = left;
  85. this.Top = top;
  86. this.Right = right;
  87. this.Bottom = bottom;
  88. }
  89. public Rectangle AsRectangle
  90. {
  91. get
  92. {
  93. return new Rectangle(this.Left, this.Top, this.Right - this.Left, this.Bottom - this.Top);
  94. }
  95. }
  96. public static RECT FromXYWH(int x, int y, int width, int height)
  97. {
  98. return new RECT(x, y, x + width, y + height);
  99. }
  100. public static RECT FromRectangle(Rectangle rect)
  101. {
  102. return new RECT(rect.Left, rect.Top, rect.Right, rect.Bottom);
  103. }
  104. }
  105. [System.Security.SuppressUnmanagedCodeSecurity()]
  106. internal sealed class NativeMethods
  107. {
  108. [DllImport("user32.dll")]
  109. internal static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
  110. [DllImport("user32.dll")]
  111. [return: MarshalAs(UnmanagedType.Bool)]
  112. internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
  113. /// <summary>
  114. /// Get a windows client rectangle in a .NET structure
  115. /// </summary>
  116. /// <param name="hwnd">The window handle to look up</param>
  117. /// <returns>The rectangle</returns>
  118. internal static Rectangle GetClientRect(IntPtr hwnd)
  119. {
  120. RECT rect = new RECT();
  121. GetClientRect(hwnd, out rect);
  122. return rect.AsRectangle;
  123. }
  124. /// <summary>
  125. /// Get a windows rectangle in a .NET structure
  126. /// </summary>
  127. /// <param name="hwnd">The window handle to look up</param>
  128. /// <returns>The rectangle</returns>
  129. internal static Rectangle GetWindowRect(IntPtr hwnd)
  130. {
  131. RECT rect = new RECT();
  132. GetWindowRect(hwnd, out rect);
  133. return rect.AsRectangle;
  134. }
  135. internal static Rectangle GetAbsoluteClientRect(IntPtr hWnd)
  136. {
  137. Rectangle windowRect = NativeMethods.GetWindowRect(hWnd);
  138. Rectangle clientRect = NativeMethods.GetClientRect(hWnd);
  139. // This gives us the width of the left, right and bottom chrome - we can then determine the top height
  140. int chromeWidth = (int)((windowRect.Width - clientRect.Width) / 2);
  141. return new Rectangle(new Point(windowRect.X + chromeWidth, windowRect.Y + (windowRect.Height - clientRect.Height - chromeWidth)), clientRect.Size);
  142. }
  143. }
  144. #endregion
  145. }
то сразу же получаю ошибку:
Ошибка CS0246 Не удалось найти тип или имя пространства имен "SlimDX" (возможно, отсутствует директива using или ссылка на сборку)
Как так? Ведь парой шагов ранее я уже установил SlimDX Runtime .NET 4.0 x64 (January 2012).msi, или этого не достаточно?? Sorry за много текста, повторю задачу: необходимо получать скриншоты рабочего стола, на котором крутятся некоторые оконные программы и "для контроля" окрыты гаджеты рабочего стола Win7 часы с календарем. Как "проще всего" это можно реализовать??

Решение задачи: «Скриншот гаджетов рабочего стола windows 7»

textual
Листинг программы
  1.         private void button1_Click(object sender, EventArgs e)
  2.         {
  3.             using (Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height))
  4.             {
  5.                 using (Graphics graphics = Graphics.FromImage(printscreen as Image))
  6.                 {
  7.                     graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
  8.                     printscreen.Save(@"screenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
  9.                 }
  10.             }
  11.         }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы