-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
367 lines (317 loc) · 12.6 KB
/
Program.cs
File metadata and controls
367 lines (317 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Configuration;
using System.Diagnostics;
namespace ImageSorterApp
{
public class StartupForm : Form
{
private TextBox _sourceTextBox;
private TextBox _outputTextBox;
private Button _selectSourceButton;
private Button _selectOutputButton;
private Button _continueButton;
public string SourceFolderPath { get; private set; }
public string OutputFolderPath { get; private set; }
public StartupForm()
{
Text = "Настройка путей";
Width = 500;
Height = 200;
Label sourceLabel = new Label { Text = "Выберите папку с изображениями:", Left = 20, Top = 0, Width = 350 };
_sourceTextBox = new TextBox { Left = 20, Top = 20, Width = 350 };
_selectSourceButton = new Button { Text = "...", Left = 380, Top = 18, Width = 50 };
_selectSourceButton.Click += (s, e) => SelectFolder(_sourceTextBox);
Label outputLabel = new Label { Text = "Выберите папку для сохранения изображений:", Left = 20, Top = 40, Width = 350 };
_outputTextBox = new TextBox { Left = 20, Top = 60, Width = 350 };
_selectOutputButton = new Button { Text = "...", Left = 380, Top = 58, Width = 50 };
_selectOutputButton.Click += (s, e) => SelectFolder(_outputTextBox);
_continueButton = new Button { Text = "Далее", Left = 200, Top = 100, Width = 100 };
_continueButton.Click += ContinueButton_Click;
Label instructionLabel = new Label
{
Text = "Управление: ← (назад), → (вперёд), ↑ (сохранить), ↓ (удалить), Esc (выход)",
Left = 20,
Top = 140,
Width = 450
};
Controls.Add(sourceLabel);
Controls.Add(_sourceTextBox);
Controls.Add(_selectSourceButton);
Controls.Add(outputLabel);
Controls.Add(_outputTextBox);
Controls.Add(_selectOutputButton);
Controls.Add(_continueButton);
Controls.Add(instructionLabel);
_sourceTextBox.Text = ConfigurationManager.AppSettings["SourceFolderPath"];
_outputTextBox.Text = ConfigurationManager.AppSettings["OutputFolderPath"];
}
private void SelectFolder(TextBox textBox)
{
using (var folderDialog = new FolderBrowserDialog())
{
if (folderDialog.ShowDialog() == DialogResult.OK)
{
textBox.Text = folderDialog.SelectedPath;
}
}
}
private void ContinueButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(_sourceTextBox.Text) || string.IsNullOrEmpty(_outputTextBox.Text))
{
MessageBox.Show("Выберите обе папки.");
return;
}
SaveSetting("SourceFolderPath", _sourceTextBox.Text);
SaveSetting("OutputFolderPath", _outputTextBox.Text);
SourceFolderPath = _sourceTextBox.Text;
OutputFolderPath = _outputTextBox.Text;
DialogResult = DialogResult.OK;
Close();
}
private void SaveSetting(string key, string value)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[key].Value = value;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
}
public class ImageSorterForm : Form
{
private string[] _imageFiles;
private int _currentIndex = 0;
private string _outputFolderPath;
private string _sourceFolderPath;
private PictureBox _pictureBox;
private Label _notificationLabel;
public ImageSorterForm(string sourceFolderPath, string outputFolderPath)
{
_sourceFolderPath = sourceFolderPath;
_outputFolderPath = outputFolderPath;
Text = "Image Sorter";
_pictureBox = new PictureBox
{
Dock = DockStyle.Fill,
SizeMode = PictureBoxSizeMode.Zoom
};
Controls.Add(_pictureBox);
_notificationLabel = new Label
{
AutoSize = true,
ForeColor = Color.White,
BackColor = Color.Black,
Padding = new Padding(10),
Visible = false,
Top = 10,
Left = Width - 250
};
Controls.Add(_notificationLabel);
LoadImages();
LoadImage();
KeyDown += OnKeyDown;
Resize += (s, e) => LoadImage();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
// Если пользователь пытается закрыть форму (через крестик или Alt + F4)
if (e.CloseReason == CloseReason.UserClosing)
{
// Создаем пользовательскую форму для подтверждения закрытия
var confirmForm = new Form()
{
Text = "Подтверждение",
Width = 350,
Height = 150,
FormBorderStyle = FormBorderStyle.FixedDialog,
StartPosition = FormStartPosition.CenterParent,
MaximizeBox = false,
MinimizeBox = false
};
var messageLabel = new Label()
{
Text = "Выберите действие:",
Left = 20,
Top = 20,
AutoSize = true
};
var exitButton = new Button()
{
Text = "Выйти",
Left = 20,
Top = 60,
Width = 90,
DialogResult = DialogResult.Yes
};
var restartButton = new Button()
{
Text = "Перезапустить",
Left = 130,
Top = 60,
Width = 90,
DialogResult = DialogResult.Retry
};
var cancelButton = new Button()
{
Text = "Отмена",
Left = 240,
Top = 60,
Width = 90,
DialogResult = DialogResult.Cancel
};
exitButton.Click += (s, ev) => { confirmForm.Close(); };
restartButton.Click += (s, ev) => { confirmForm.Close(); };
cancelButton.Click += (s, ev) => { confirmForm.Close(); };
confirmForm.Controls.Add(messageLabel);
confirmForm.Controls.Add(exitButton);
confirmForm.Controls.Add(restartButton);
confirmForm.Controls.Add(cancelButton);
confirmForm.AcceptButton = cancelButton;
var result = confirmForm.ShowDialog(this);
if (result == DialogResult.Yes) // Выйти
{
DeleteViewedImages();
}
else if (result == DialogResult.Retry) // Перезапустить
{
DeleteViewedImages();
e.Cancel = true;
Application.Restart();
}
else // Отмена
{
e.Cancel = true;
}
}
}
private void LoadImages()
{
_imageFiles = Directory.GetFiles(_sourceFolderPath, "*.*")
.Where(f => f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
f.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
.ToArray();
if (_imageFiles.Length == 0)
{
MessageBox.Show("В папке нет изображений.");
Close();
}
}
private Image _currentImage;
private bool _isGifAnimated;
private void LoadImage()
{
if (_imageFiles.Length > 0 && _currentIndex >= 0 && _currentIndex < _imageFiles.Length)
{
_pictureBox.Image?.Dispose(); // Освобождаем память от предыдущего изображения
_isGifAnimated = false; // Сбрасываем флаг анимации
string currentFile = _imageFiles[_currentIndex];
try
{
if (currentFile.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
{
_currentImage?.Dispose(); // Удаляем предыдущее изображение
_currentImage = Image.FromFile(currentFile); // Загружаем новое изображение
_pictureBox.Image = _currentImage;
// Проверяем, является ли изображение анимированным GIF
if (ImageAnimator.CanAnimate(_currentImage))
{
_isGifAnimated = true;
ImageAnimator.Animate(_currentImage, OnFrameChanged);
}
}
else
{
_currentImage?.Dispose();
_currentImage = Image.FromFile(currentFile);
_pictureBox.Image = _currentImage;
}
// Настраиваем режим отображения
_pictureBox.SizeMode = _currentImage.Width < 700 && _currentImage.Height < 700
? PictureBoxSizeMode.CenterImage
: PictureBoxSizeMode.Zoom;
Text = $"Image {(_currentIndex + 1)} of {_imageFiles.Length}";
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка загрузки изображения: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
// Метод обновления кадра GIF
private void OnFrameChanged(object sender, EventArgs e)
{
if (_isGifAnimated)
{
_pictureBox.Invalidate(); // Перерисовка PictureBox для обновления кадра GIF
}
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
if (_currentIndex > 0) _currentIndex--;
LoadImage();
break;
case Keys.Right:
if (_currentIndex < _imageFiles.Length - 1) _currentIndex++;
LoadImage();
break;
case Keys.Up:
SaveCurrentImage();
break;
case Keys.Down:
DeleteSavedImage();
break;
case Keys.Escape:
// DeleteViewedImages();
Close();
break;
}
}
private void SaveCurrentImage()
{
string destFile = Path.Combine(_outputFolderPath, Path.GetFileName(_imageFiles[_currentIndex]));
if (!File.Exists(destFile)) File.Copy(_imageFiles[_currentIndex], destFile);
}
private void DeleteSavedImage()
{
string destFile = Path.Combine(_outputFolderPath, Path.GetFileName(_imageFiles[_currentIndex]));
if (File.Exists(destFile)) File.Delete(destFile);
}
private void DeleteViewedImages()
{
_pictureBox.Image?.Dispose();
for (int i = 0; i <= _currentIndex; i++)
{
try
{
File.Delete(_imageFiles[i]);
}
catch (Exception ex)
{
}
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (var startupForm = new StartupForm())
{
if (startupForm.ShowDialog() == DialogResult.OK)
{
Application.Run(new ImageSorterForm(startupForm.SourceFolderPath, startupForm.OutputFolderPath));
}
}
}
}
}