I need to figure out a safe way to write code to find a folder and close it. I am getting an error on PostMessage method because IntPtr cannot be assigned to HandleRef object. I am clueless on how to fix this issue.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PostMessage(HandleRef hWnd, uint msg, IntPtr wParam, IntPtr lParam);
private const int WM_CLOSE = 0xF060;
void PostMessageSafe(HandleRef hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
bool returnValue = PostMessage(hWnd, msg, wParam, lParam);
if (!returnValue)
{
Console.WriteLine("Some error occurred.");
}
}
static void Main(string[] args)
{
var path = @"C:\deleteme\";
Process.Start(path);
IntPtr hWnd = FindWindow(null, "deleteme");
if (hWnd != IntPtr.Zero)
{
PostMessageSafe(hWnd, WM_CLOSE, 0, 0); // Error
Console.Write("Success!\n");
Console.ReadLine();
}
else
{
Console.Write("Error Folder not found!\n");
Console.ReadLine();
}
}
}
}