Загрузка данных


using ImageMagick;
using FFMpegCore;
using Spire.Doc;
using Spire.Presentation;

namespace UltraConvert
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SetupTools();
            
            // Настройка списка форматов, если вдруг забыл в дизайнере
            if (comboBoxFormats.Items.Count == 0)
            {
                comboBoxFormats.Items.AddRange(new object[] { 
                    "В JPEG (из Фото)", 
                    "В PDF (из DOCX/PPTX)", 
                    "В MP3 (из Видео)" 
                });
                comboBoxFormats.SelectedIndex = 0;
            }
        }

        private void SetupTools()
        {
            // Указываем программе искать движки в своей же папке
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            MagickNET.SetGhostscriptDirectory(baseDir);
            GlobalFFOptions.Configure(options => options.BinaryFolder = baseDir);
        }

        // Кнопка добавления файлов в очередь
        private void btnSelectFiles_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog { Multiselect = true })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    foreach (string file in ofd.FileNames)
                    {
                        if (!listBoxQueue.Items.Contains(file))
                            listBoxQueue.Items.Add(file);
                    }
                }
            }
        }

        // Кнопка очистки очереди
        private void btnClear_Click(object sender, EventArgs e)
        {
            listBoxQueue.Items.Clear();
            lblStatus.Text = "Очередь пуста";
        }

        // Главная кнопка конвертации
        private async void btnConvert_Click(object sender, EventArgs e)
        {
            if (listBoxQueue.Items.Count == 0)
            {
                MessageBox.Show("Добавь файлы в очередь!");
                return;
            }

            btnConvert.Enabled = false;
            int total = listBoxQueue.Items.Count;

            for (int i = 0; i < total; i++)
            {
                string filePath = listBoxQueue.Items[i].ToString();
                lblStatus.Text = $"Обработка {i + 1} из {total}: {Path.GetFileName(filePath)}";

                try
                {
                    // Запускаем задачу в фоне, чтобы интерфейс не зависал
                    await Task.Run(() => ProcessSingleFile(filePath));
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка в файле {Path.GetFileName(filePath)}: {ex.Message}");
                }
            }

            lblStatus.Text = "Готово!";
            btnConvert.Enabled = true;
            MessageBox.Show("Все файлы обработаны!", "Успех");
        }

        private void ProcessSingleFile(string input)
        {
            string folder = Path.GetDirectoryName(input);
            string fileName = Path.GetFileNameWithoutExtension(input);
            int selectedMode = 0;

            // Читаем выбор из ComboBox безопасно из другого потока
            this.Invoke(new Action(() => { selectedMode = comboBoxFormats.SelectedIndex; }));

            switch (selectedMode)
            {
                case 0: // В JPEG
                    using (var img = new MagickImage(input))
                    {
                        img.Format = MagickFormat.Jpeg;
                        img.Write(Path.Combine(folder, fileName + ".jpg"));
                    }
                    break;

                case 1: // В PDF
                    string ext = Path.GetExtension(input).ToLower();
                    string outPdf = Path.Combine(folder, fileName + ".pdf");
                    
                    if (ext == ".docx" || ext == ".doc")
                    {
                        Document doc = new Document();
                        doc.LoadFromFile(input);
                        doc.SaveToFile(outPdf, Spire.Doc.FileFormat.PDF);
                    }
                    else if (ext == ".pptx")
                    {
                        Presentation ppt = new Presentation();
                        ppt.LoadFromFile(input);
                        ppt.SaveToFile(outPdf, Spire.Presentation.FileFormat.PDF);
                    }
                    break;

                case 2: // В MP3
                    FFMpeg.ExtractAudio(input, Path.Combine(folder, fileName + ".mp3"));
                    break;
            }
        }
    }
}