응용 프로그램 A (예 : AutoCAD, Word, ...)가 실행되면 런타임에 DLL X를 호출하여 작업 수행 → 양식 열기 로그인
응용 프로그램 B (예 : Photoshop, Excel ...)가 실행되면 런타임에 DLL Y를 호출하여 작업을 수행합니다. → 위의 로그인 양식을 닫고 싶습니다. 이렇게 할 수 있습니까?
가능합니까?
다음은 다른 프로세스에서 창을 닫는 방법을 보여주는 작은 샘플입니다. 새 Windows Forms 프로젝트를 만들고 두 개의 Forms를 추가하고 첫 번째 단추에 두 개의 단추를 추가하고 해당 코드를 Form1에 넣습니다.
public partial class Form1 : Form
{
delegate bool EnumWindowsProc(IntPtr Hwnd, IntPtr lParam);
[DllImport("user32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool EnumThreadWindows(int threadId, EnumWindowsProc callback, IntPtr lParam);
[DllImport("user32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32", SetLastError = true, CharSet = CharSet.Auto)]
private extern static int GetWindowText(IntPtr hWnd, StringBuilder text, int maxCount);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
private const int WM_CLOSE = 0x10;
public Form1()
{
InitializeComponent();
button1.Click += button1_Click;
button2.Click += button2_Click;
}
private void button1_Click(object sender, EventArgs e)
{
var frm = new Form2();
frm.Show(this);
}
private void button2_Click(object sender, EventArgs e)
{
Process[] processes = Process.GetProcessesByName("FindWindowSample");
foreach (Process p in processes)
{
var handle = FindWindowInProcess(p, x => x == "Form2");
if (handle != IntPtr.Zero)
{
SendMessage(handle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
}
}
public static IntPtr FindWindowInProcess(Process process, Func<string, bool> compareTitle)
{
IntPtr windowHandle = IntPtr.Zero;
foreach (ProcessThread t in process.Threads)
{
windowHandle = FindWindowInThread(t.Id, compareTitle);
if (windowHandle != IntPtr.Zero)
{
break;
}
}
return windowHandle;
}
private static IntPtr FindWindowInThread(int threadId, Func<string, bool> compareTitle)
{
IntPtr windowHandle = IntPtr.Zero;
EnumThreadWindows(threadId, (hWnd, lParam) =>
{
StringBuilder text = new StringBuilder(200);
GetWindowText(hWnd, text, 200);
if (compareTitle(text.ToString()))
{
windowHandle = hWnd;
return false;
}
return true;
}, IntPtr.Zero);
return windowHandle;
}
}
응용 프로그램의 두 인스턴스를 컴파일 한 다음 실행합니다. 첫 번째에서 Button1을 클릭하여 Form2를 표시합니다. 두 번째 인스턴스에서 Button2를 클릭하여 첫 번째 인스턴스에서 Form2를 닫습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다