Reputation: 228
i want to focus a program from my c# application.i searched lot and found some examples.but i got error .i'm using visual studio.ShowWindow(hWnd, SW_HIDE);
line gives me an error "showwindow(system.IntPtr,int) has some invalid argument"
plz where is the problem of this code
[DllImport("user32.dll")]
internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private void FocusProcess()
{
int hWnd;
Process[] processRunning = Process.GetProcesses();
foreach (Process pr in processRunning)
{
if (pr.ProcessName == "notepad")
{
hWnd = pr.MainWindowHandle.ToInt32();
ShowWindow(hWnd, 3);//error line
}
}
}
Upvotes: 3
Views: 11620
Reputation: 53
You declared hWnd as int. But the ShowWindow function needs an IntPtr. Because pr.MainWindowHandle is an IntPtr you just need to use it as hWnd. Btw. if you want this window as the topmost you should call SetForegroundWindow.
[DllImport("user32.dll")]
internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); //ShowWindow needs an IntPtr
private static void FocusProcess()
{
IntPtr hWnd; //change this to IntPtr
Process[] processRunning = Process.GetProcesses();
foreach (Process pr in processRunning)
{
if (pr.ProcessName == "notepad")
{
hWnd = pr.MainWindowHandle; //use it as IntPtr not int
ShowWindow(hWnd, 3);
SetForegroundWindow(hWnd); //set to topmost
}
}
}
Upvotes: 3