2012-06-05 103 views
7

我有一個程序失去了重點的問題。這不是我的計劃。我如何編寫第二個程序,每隔1-2秒將焦點設置到該窗口?有可能做到這一點嗎?如何將焦點設置到另一個窗口?

+0

你是說你想讓焦點在你的程序和其他第二個程序之間每隔一秒進行一次切換嗎?或者在你的應用程序中想每隔2秒將其他程序放在前面(以防再次返回)? – Faraday

+0

它是一個程序(不同的程序過程)還是你的孩子形式? –

+0

它的不同的程序,我想我的程序只能把它聚焦...... – Endiss

回答

8

你可以,如果你想帶一些其他程序/過程

 [DllImport("coredll.dll")] 
     static extern bool SetForegroundWindow (IntPtr hWnd); 

     private void BringToFront(Process pTemp) 
     { 
      SetForegroundWindow(pTemp.MainWindowHandle); 
     } 
+11

在Windows上,你應該使用'user32.dll',因爲'coredll.dll'是Windows Mobile的! –

2

使用間諜++或其他UI工具,以找到您想要對焦的窗口類名使用下面的Win32 API,說其:focusWindowClassName 。然後添加以下功能:

[DllImport("USER32.DLL")] 
public static extern bool SetForegroundWindow(IntPtr hWnd); 

[System.Runtime.InteropServices.DllImport("User32.dll")] 
public static extern bool ShowWindow(IntPtr handle, int nCmdShow); 

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] 
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 

Then: 

IntPrt hWnd = FindWindow("focusWindowClassName", null); // this gives you the handle of the window you need. 

// then use this handle to bring the window to focus or forground(I guessed you wanted this). 

// sometimes the window may be minimized and the setforground function cannot bring it to focus so: 

/*use this ShowWindow(IntPtr handle, int nCmdShow); 
*there are various values of nCmdShow 3, 5 ,9. What 9 does is: 
*Activates and displays the window. If the window is minimized or maximized, *the system restores it to its original size and position. An application *should specify this flag when restoring a minimized window */ 

ShowWindow(hWnd, 9); 
//The bring the application to focus 
SetForegroundWindow(hWnd); 

// you wanted to bring the application to focus every 2 or few second 
// call other window as done above and recall this window again. 
相關問題