d

mail@pastecode.io avatarunknown
csharp
a month ago
1.8 kB
4
Indexable
Never
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string? lpClassName, string lpWindowName);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    const uint WM_CLOSE = 0x0010;

    static void Main(string[] args)
    {
        // Close Excel.exe process
        CloseExcelProcess();

        // Wait for the Excel prompt window and click "Don't Save"
        WaitForAndClickDontSave();
    }

    static void CloseExcelProcess()
    {
        Process[] processes = Process.GetProcessesByName("EXCEL");

        foreach (Process process in processes)
        {
            process.CloseMainWindow();

            if (!process.WaitForExit(12000))
            {
                process.Kill();
            }
        }
    }

    static void WaitForAndClickDontSave()
    {
        IntPtr excelWindow = IntPtr.Zero;

        while (excelWindow == IntPtr.Zero)
        {
            excelWindow = FindWindow(null, "Microsoft Excel");
            System.Threading.Thread.Sleep(100);
        }

        IntPtr dontSaveButton = FindWindow("#32770", "Microsoft Excel");
        dontSaveButton = FindWindowEx(dontSaveButton, IntPtr.Zero, "Button", "Don't Save");

        if (dontSaveButton != IntPtr.Zero)
        {
            SendMessage(dontSaveButton, 0xf5, IntPtr.Zero, IntPtr.Zero);
        }
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
}