2012-02-23 105 views
2

我需要一個通過打開的資源管理器窗口枚舉的功能。這裏是我有一個代碼:什麼是此lambda表達式的C#2.0等效代碼

delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam); 

[DllImport("user32.dll")] 
static extern bool EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam); 

static IEnumerable<IntPtr> EnumerateProcessWindowHandles(int processID) 
{ 
    List<IntPtr> handles = new List<IntPtr>(); 

    foreach (ProcessThread thread in Process.GetProcessById(processID).Threads) 
    {        //what is the magic going on beneath this?? :o 
     EnumThreadWindows(thread.Id, (hWnd, lParam) => { handles.Add(hWnd); return true;}, IntPtr.Zero); 
    } 
    return handles; 
} 

和代碼繼續在這裏是這樣的:

[DllImport("coredll.dll")] 
static extern int ShowWindow(IntPtr hWnd, int nCmdShow); 

const int SW_MINIMIZED = 6; 

private void button1_Click(object sender, EventArgs e) 
{ 
    foreach (IntPtr handle in EnumerateProcessWindowHandles(Process.GetProcessesByName("explorer")[0].Id)) 
    { 
     ShowWindow(handle, SW_MINIMIZED); 
    } 
} 

我的問題是,在第一個代碼塊,我怎麼更換lambda表達式這樣我可以在VS使用C#2.0編譯代碼2005

回答

1
delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam); 

static IEnumerable<IntPtr> EnumerateProcessWindowHandles(int processID) 
{ 
    List<IntPtr> handles = new List<IntPtr>(); 

    EnumThreadDelegate addWindowHandle = delegate(IntPtr hWnd, IntPtr param) 
    { 
     handles.Add(hWnd); 
     return true; 
    }; 

    foreach (ProcessThread thread in Process.GetProcessById(processID).Threads) 
    { 
     EnumThreadWindows(thread.Id, addWindowHandle, IntPtr.Zero); 
    } 
    return handles; 
} 
+0

這似乎正是我」正在尋找!我會盡快回復 – nawfal 2012-02-23 14:55:05

2

創建一個新的方法,以進入EnumThreadWindows這樣的:

static bool EnumThreadCallback(IntPtr hWnd, IntPtr lParam) 
{ 
    // Close the enumerated window. 
    PostMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); 

    return true; 
} 

並做好委託來與它一起去:

public delegate bool EnumThreadDelegate (IntPtr hWnd, IntPtr lParam); 

然後調用這樣的功能:

foreach (ProcessThread pt in proc.Threads) 
{ 
    EnumThreadWindows((uint)pt.Id, new EnumThreadDelegate(EnumThreadCallback), IntPtr.Zero); 
} 

來源:http://www.pinvoke.net/default.aspx/user32/EnumThreadWindows.html

相關問題