Служба скриншот рабочего стола - C#

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

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

Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.ServiceProcess;
  8. using System.Text;
  9. using System.Threading;
  10. using System.IO;
  11. using System.Drawing;
  12. using System.Drawing.Imaging;
  13. using System.Windows.Forms;
  14. namespace Service
  15. {
  16. public partial class Service : ServiceBase
  17. {
  18. private StreamWriter file;
  19. //Определяем таймер
  20. private System.Timers.Timer timer1;
  21. public Service()
  22. {
  23. InitializeComponent();
  24. }
  25. static string GenerateRandomJpegName()
  26. {
  27. return GenerateRandomString() + ".jpg";
  28. }
  29. static string GenerateRandomString()
  30. {
  31. bool UseSigns = true;
  32. bool UseUpperLetters = true;
  33. bool UseLetters = true;
  34. int Length;
  35. NewLabel:
  36. try
  37. {
  38. Length = new Random(DateTime.Now.Millisecond - DateTime.Now.Second + new Random(DateTime.Now.Millisecond).Next(0, 100) / new Random(DateTime.Now.Millisecond - DateTime.Now.Second).Next(0, 10)).Next(0, 100);
  39. }
  40. catch { goto NewLabel; }
  41. string result = "C:/";
  42. try
  43. {
  44. int Seed = 0;
  45. char[] letters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
  46. char[] signs = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
  47. List<char> keyWords = new List<char>();
  48. List<char> upperLetters = new List<char>();
  49. foreach (char c in letters)
  50. upperLetters.Add(Convert.ToChar(c.ToString().ToUpper()));
  51. if (UseLetters)
  52. foreach (char c in letters)
  53. keyWords.Add(c);
  54. if (UseSigns)
  55. foreach (char c in signs)
  56. keyWords.Add(c);
  57. if (UseUpperLetters)
  58. foreach (char c in upperLetters)
  59. keyWords.Add(c);
  60. int MaxValue = keyWords.Count;
  61. for (int i = 0; i <= Length; i++)
  62. {
  63. try
  64. {
  65. Random mainrand = new Random(Seed);
  66. char RandChar = keyWords[mainrand.Next(0, MaxValue)];
  67. result += RandChar;
  68. Seed += DateTime.Now.Millisecond + Seed - new Random().Next(10) + new Random(DateTime.Now.Millisecond + 800 * 989 / 3).Next(10);
  69. }
  70. catch { continue; }
  71. }
  72. }
  73. catch { }
  74. return result;
  75. }
  76. static void Main()
  77. {
  78. }
  79. protected override void OnStart(string[] args)
  80. {
  81. //Файл по умолчанию будет создан в "C:\Windows\SysWOW6"
  82. file = new StreamWriter(new FileStream("Service.log", System.IO.FileMode.Append));
  83. this.file.WriteLine("Service стартовал");
  84. this.file.Flush();
  85. //Создаем таймер и выставляем его параметры
  86. this.timer1 = new System.Timers.Timer();
  87. this.timer1.Enabled = true;
  88. //Интервал 10000мс - 10с.
  89. this.timer1.Interval = 100000;
  90. this.timer1.Elapsed +=
  91. new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
  92. this.timer1.AutoReset = true;
  93. this.timer1.Start();
  94. Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
  95. Graphics g = Graphics.FromImage(bmp);
  96. g.CopyFromScreen(0, 0, Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
  97. bmp.Save(GenerateRandomJpegName(), ImageFormat.Jpeg);
  98. }
  99. protected override void OnStop()
  100. {
  101. this.timer1.Stop();
  102. this.file.WriteLine("Service остановлен");
  103. this.file.Flush();
  104. this.file.Close();
  105. }
  106. private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  107. {
  108. //Записываем время в файл или делаем все, что хотим
  109. this.file.WriteLine(DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"));
  110. this.file.Flush();
  111. }
  112. }
  113. }
создал службу, установил. Не запускается служба. в чем проблема? кто нибудь подскажите.

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

textual
Листинг программы
  1.  private void serviceInstaller1_Committed(object sender, InstallEventArgs e)
  2.         {
  3.             string serviceName = "MyRss";
  4.             ManagementObjectSearcher ms =
  5.                 new ManagementObjectSearcher("SELECT * FROM Win32_Service WHERE DisplayName = '" + serviceName + "'");
  6.             foreach (ManagementObject mo in ms.Get())
  7.             {
  8.                 ManagementObject inParams = (ManagementObject)mo.GetMethodParameters("Change");
  9.                 inParams["DesktopInteract"] = true;
  10.                 mo.InvokeMethod("Change", inParams, null);
  11.                 break;
  12.             }
  13.         }

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


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

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

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

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

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

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