ProgressForm Code Help

iEmby wrote on 9/2/2024, 4:22 AM

Hi guys...

i created a form names progressForm.

i add in this a label and a progress bar

this is the code

using System;
using System.Windows.Forms;

namespace MiniTools
{
    public partial class ProgressForm : Form
    {
        private readonly Timer updateTimer;
        private string progressMessage;
        private bool isUpdating;
        private int taskCount;
        private int currentTask;

        public ProgressForm()
        {
            InitializeComponent();

            // Initialize Timer
            updateTimer = new Timer();
            updateTimer.Interval = 1000; // 1 second
            updateTimer.Tick += UpdateTimer_Tick;
            updateTimer.Start();

            // Set initial message
            progressMessage = "Please wait...";
            isUpdating = false;
            taskCount = 0;
            currentTask = 0;

            // Set form properties to make it modal and prevent user interaction
            this.FormBorderStyle = FormBorderStyle.FixedDialog; // Make the window fixed size
            this.ControlBox = false; // Disable close button
            this.StartPosition = FormStartPosition.CenterScreen; // Center the form
        }

        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            if (!isUpdating)
            {
                // Show "Please Wait..." message
                statusLabel.Text = progressMessage;
            }
        }

        public void UpdateProgress(string message, int taskIndex, int totalTasks)
        {
            progressMessage = message;
            isUpdating = true;
            statusLabel.Text = message;

            // Update Progress Bar
            taskCount = totalTasks > 100 ? 100 : totalTasks; // If tasks are more than 100, set taskCount to 100
            currentTask = taskIndex;
            int progressValue = totalTasks > 100 ? (int)((double)taskIndex / totalTasks * 100) : taskIndex;

            progressBar.Value = Math.Min(progressValue, 100); // Ensure the value does not exceed 100

            // Reset the timer
            updateTimer.Stop();
            updateTimer.Start();
            isUpdating = false;

            // Close form automatically when all tasks are complete
            if (taskIndex >= totalTasks)
            {
                Close();
            }
        }
    }
}

and this is how i handel it

 

public async void SaveSnapshots(Vegas vegas)
{
    using (ProgressForm progressForm = new ProgressForm())
    {
        progressForm.Show(); // Show the progress form in non-modal mode

        try
        {
            // Save original project and project settings
            VideoRenderQuality originalPreviewRenderQuality = vegas.Project.Preview.RenderQuality;
            bool originalPreviewFillSize = vegas.Project.Preview.FullSize;

            // Set preview quality and size
            vegas.Project.Preview.RenderQuality = VideoRenderQuality.Best;
            vegas.Project.Preview.FullSize = true;
            vegas.UpdateUI();

            // Create 'Snapshots' folder in the project directory if it doesn't exist
            string snapshotFolder = Path.Combine(Path.GetDirectoryName(vegas.Project.FilePath), "Snapshots");

            if (!Directory.Exists(snapshotFolder))
            {
                Directory.CreateDirectory(snapshotFolder);
            }

            // Get the existing snapshot files
            string[] existingSnapshots = Directory.GetFiles(snapshotFolder, "Snapshot-*.jpg");

            // Determine the starting counter based on existing snapshots
            int snapshotCounter = existingSnapshots.Length + 1;

            // Update progress form
            progressForm.UpdateProgress("Saving snapshots...", 0, vegas.Project.Markers.Count);

            // Run the snapshot saving process in a background thread
            await Task.Run(() =>
            {
                int currentMarkerIndex = 0;
                foreach (Marker marker in vegas.Project.Markers)
                {
                    try
                    {
                        // Set the cursor time to the marker position
                        vegas.Transport.CursorPosition = marker.Position;

                        // Create snapshot file name
                        string snapshotFilePath = Path.Combine(snapshotFolder, $"Snapshot-{snapshotCounter}.jpg");

                        // Increment the counter for the next snapshot
                        snapshotCounter++;

                        // Save the snapshot
                        vegas.SaveSnapshot(snapshotFilePath, ImageFileFormat.JPEG, vegas.Transport.CursorPosition);

                        // Update progress on the UI thread
                        progressForm.Invoke((Action)(() =>
                        {
                            currentMarkerIndex++;
                            progressForm.UpdateProgress($"Saving snapshot {currentMarkerIndex}...", currentMarkerIndex, vegas.Project.Markers.Count);
                        }));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Error saving snapshot at marker: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            });

            // Restore project preview quality setting
            vegas.Project.Preview.RenderQuality = originalPreviewRenderQuality;
            vegas.Project.Preview.FullSize = originalPreviewFillSize;
            vegas.UpdateUI();

            progressForm.UpdateProgress("Snapshots saved successfully!", vegas.Project.Markers.Count, vegas.Project.Markers.Count);
        }
        catch (Exception ex)
        {
            // Display an error message if something goes wrong
            MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            // Ensure the progress form is closed
            progressForm.Close();
        }
    }
}

the problem is i want when this form launches it should freeze everything to reach in VEGAS until form closed automatically.

but is blocking UI thread when i use ShowDialog() and it freeze VEGAS and but when i user show() then it working but if i move the progressForm dialog while its processing. it again got freezed and crashed.

i am so confused.

can anybody guide me in this...

PROCESSOR
     

Operating System: Windows 11 Pro 64-bit (Always Updated)
System Manufacturer: ASUS
12th Gen Intel(R) Core(TM) i7-12700 (20 CPUs), ~2.1GHz - 4.90GHz
Memory: 32GB RAM
Page File: 11134MB used, 7934MB Available
DirectX Version: DirectX 12

-----------------------------------------------

MOTHERBOARD

 

ASUS PRIME H610-CS D4
Intel® H610 (LGA 1700)
Ready for 12th Gen Intel® Processors
Micro-ATX Motherboard with DDR4
Realtek 1 Gb Ethernet
PCH Heatsink
PCIe 4.0 | M.2 slot (32Gbps) 
HDMI® | D-Sub | USB 3.2 Gen 1 ports
SATA 6 Gbps | COM header
LPT header | TPM header
Luminous Anti-Moisture Coating
5X Protection III
(Multiple Hardware Safeguards
For all-round protection)

-----------------------------------------------
EXTERNAL GRAPHIC CARD

-----------------------------------------------

INTERNAL GRAPHIC CARD (iGPU)

------------------------------------------------

LED - MONITOR

Monitor Name: Generic PnP Monitor
Monitor Model: HP 22es
Monitor Id: HWP331B
Native Mode: 1920 x 1080(p) (60.000Hz)
Output Type: HDMI

-----------------------------------------------

STORAGE DRIVE

Drive: C:
Free Space: 182.3 GB
Total Space: 253.9 GB
File System: NTFS
Model: WD Blue SN570 1TB (NVMe)

---------------O----------------

My System Info (PDF File).

https://drive.google.com/open?id=1-eoLmuXzshTRH_8RunAYAuNocKpiLoiV&usp=drive_fs

 

Also Check

Some useful creations by me including VEGAS Scripts

https://getopensofts.blogspot.com/

 

My YouTube Channel Dedicated to Only VEGAS Pro Tutorials

EDITROOM : My YouTube Channel (For VEGAS Tutorials)

Comments

iEmby wrote on 9/5/2024, 2:47 AM

@jetdv @zzzzzz9125 @Thiago_Sase

please check..

PROCESSOR
     

Operating System: Windows 11 Pro 64-bit (Always Updated)
System Manufacturer: ASUS
12th Gen Intel(R) Core(TM) i7-12700 (20 CPUs), ~2.1GHz - 4.90GHz
Memory: 32GB RAM
Page File: 11134MB used, 7934MB Available
DirectX Version: DirectX 12

-----------------------------------------------

MOTHERBOARD

 

ASUS PRIME H610-CS D4
Intel® H610 (LGA 1700)
Ready for 12th Gen Intel® Processors
Micro-ATX Motherboard with DDR4
Realtek 1 Gb Ethernet
PCH Heatsink
PCIe 4.0 | M.2 slot (32Gbps) 
HDMI® | D-Sub | USB 3.2 Gen 1 ports
SATA 6 Gbps | COM header
LPT header | TPM header
Luminous Anti-Moisture Coating
5X Protection III
(Multiple Hardware Safeguards
For all-round protection)

-----------------------------------------------
EXTERNAL GRAPHIC CARD

-----------------------------------------------

INTERNAL GRAPHIC CARD (iGPU)

------------------------------------------------

LED - MONITOR

Monitor Name: Generic PnP Monitor
Monitor Model: HP 22es
Monitor Id: HWP331B
Native Mode: 1920 x 1080(p) (60.000Hz)
Output Type: HDMI

-----------------------------------------------

STORAGE DRIVE

Drive: C:
Free Space: 182.3 GB
Total Space: 253.9 GB
File System: NTFS
Model: WD Blue SN570 1TB (NVMe)

---------------O----------------

My System Info (PDF File).

https://drive.google.com/open?id=1-eoLmuXzshTRH_8RunAYAuNocKpiLoiV&usp=drive_fs

 

Also Check

Some useful creations by me including VEGAS Scripts

https://getopensofts.blogspot.com/

 

My YouTube Channel Dedicated to Only VEGAS Pro Tutorials

EDITROOM : My YouTube Channel (For VEGAS Tutorials)

Thiago_Sase wrote on 9/5/2024, 11:07 AM

@iEmby Hello, I don't know how to help you on that task.

i am so confused.

About that, I'm confused as well.

ChrisD wrote on 9/5/2024, 12:27 PM

but is blocking UI thread when i use ShowDialog() and it freeze VEGAS and but when i user show() then it working but if i move the progressForm dialog while its processing. it again got freezed and crashed.

I haven't parsed your script, but perhaps it is a classic threading issue with your implementation?

With Message Boxes and Progress Bars, and depending on whether you want to block or not, see if any of this helps:

https://stackoverflow.com/questions/4245138/non-autoblocking-messageboxes-in-c-sharp

https://stackoverflow.com/questions/45144549/ui-gets-blocked-while-the-progress-bar-gets-updated

jetdv wrote on 9/9/2024, 1:07 PM

@iEmby, There is an issue when the form gets moved. DO NOT MOVE the form while the snapshots are being taken. After progressForm.Show(); you might try adding progressForm.Enabled = false; and before progressForm.Close(); you can add progressForm.Enabled = true; to try and prevent the form from being moved.

But there is a (now known) issue when you move the form - when taking snapshots - that will cause an issue in VEGAS.

I have not tested this so there may be some other issues related to this code...