Conversation with Merlin · Tue Nov 28 2023

Привет! Вот у меня есть две функции private void ButtonTheEnd_Click(object sender, RoutedEventArgs e) { if (phase == 2) { System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(screenshot); graphics.CopyFromScreen(0, 0, 0, 0, screenshot.Size, System.Drawing.CopyPixelOperation.SourceCopy); SvodResult(); string exeFolderPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string screenshotPath = System.IO.Path.Combine(exeFolderPath, "screenshot.png"); screenshot.Save(screenshotPath, System.Drawing.Imaging.ImageFormat.Png); graphics.Dispose(); screenshot.Dispose(); Window1 theEndWindow = new Window1(SvodRes); theEndWindow.Show(); isFormClosing = true; string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location; string folderPath = System.IO.Path.GetDirectoryName(exePath); string templateFileName = GameField.Title + ".pptx"; string templatePath = System.IO.Path.Combine(folderPath, templateFileName); Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application(); Microsoft.Office.Interop.PowerPoint.Presentation presentation = pptApp.Presentations.Open(templatePath, WithWindow: Microsoft.Office.Core.MsoTriState.msoFalse); Microsoft.Office.Interop.PowerPoint.Slide lastSlide = presentation.Slides[presentation.Slides.Count - 1]; lastSlide.Delete(); presentation.SaveAs(templatePath); presentation.Close(); pptApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(presentation); System.Runtime.InteropServices.Marshal.ReleaseComObject(pptApp); Close();
}}

private void GameField_Closing(object sender, System.ComponentModel.CancelEventArgs e) { System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(screenshot); graphics.CopyFromScreen(0, 0, 0, 0, screenshot.Size, System.Drawing.CopyPixelOperation.SourceCopy); isFormClosing = true; SvodResult(); string exeFolderPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string screenshotPath = System.IO.Path.Combine(exeFolderPath, "screenshot.png"); screenshot.Save(screenshotPath, System.Drawing.Imaging.ImageFormat.Png); graphics.Dispose(); screenshot.Dispose(); string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location; string folderPath = System.IO.Path.GetDirectoryName(exePath); string templateFileName = GameField.Title + ".pptx"; string templatePath = System.IO.Path.Combine(folderPath, templateFileName); Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application(); Microsoft.Office.Interop.PowerPoint.Presentation presentation = pptApp.Presentations.Open(templatePath, WithWindow: Microsoft.Office.Core.MsoTriState.msoFalse); Microsoft.Office.Interop.PowerPoint.Slide lastSlide = presentation.Slides[presentation.Slides.Count - 1]; lastSlide.Delete(); presentation.SaveAs(templatePath); presentation.Close(); Window1 theEndWindow = new Window1(SvodRes); theEndWindow.Show(); } оптимизируй их так, можешь общий код вывести в отдельную функцию

Привет! Конечно, я могу помочь вам оптимизировать этот код. Чтобы переиспользовать общую логику сохранения скриншота и работы с PowerPoint презентацией, предлагаю создать метод для этой цели. Ниже представлен пример возможной оптимизации кода:

// Метод для сохранения скриншота private void SaveScreenshot(string filePath) { System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Drawing.Graphics graphics = System.Drawing.GraphicsImage(screenshot); graphics.CopyFromScreen(0, 0, 0, 0, screenshot.Size, System.Drawing.CopyPixelOperation.SourceCopy); screenshot.Save(filePath, System.Drawing.Imaging.ImageFormat.Png); graphics.Dispose(); screenshot.Dispose(); } // Метод для обработки закрытия формы private void HandleFormClosing() { if (phase == 2) { string exeFolderPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string screenshotPath = System.IO.Path.Combine(exeFolderPath, "screenshot.png"); SaveScreenshot(screenshotPath); string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location; string folderPath = System.IO.Path.GetDirectoryName(exePath); string templateFileName = GameField.Title + ".pptx"; string templatePath = System.IO.Path.Combine(folderPath, templateFileName); using (Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application()) { Microsoft.Office.Interop.PowerPoint.Presentation presentation = pptApp.Presentations.Open(templatePath, WithWindow: Microsoft.Office.Core.MsoTriState.msoFalse); Microsoft.Office.Interop.PowerPoint.Slide lastSlide = presentation.Slides[presentation.Slides.Count - 1]; lastSlide.Delete(); } ShowTheEndWindow(); Close(); } } // Обработик нажатия на кнопку "The End" private void ButtonTheEnd_Click(object sender, RoutedEventArgs e) { HandleFormClosing(); } // Обработчик закрытия GameField private void GameField_Closing(object sender, System.ComponentModel.CancelEventArgs e) { string exeFolderPath = System.IO.Path(System.Reflection.Assembly.GetExecutingAssembly().Location); string screenshotPath = System.IO.Path.Combine(exeFolderPath, "screenshot.png"); SaveScreenshot(screenshotPath); ShowTheEndWindow(); } // Метод для отображения окна завершения (The End Window) private void ShowTheEndWindow() { Window1 theEndWindow new Window1(SvodRes); theEndWindow.Show(); }

Таким образом, код сохранения скриншота и работы с PowerPoint презентей вынесен в отдельные методы, которые вызываются из обработчиков событий. Это улучшает читаемость и поддиваемость кода.