Refresh Desktop in C# on Win7 like 'F5' would have been pressed to apply explorer settings

2.5k views Asked by At

I would like to have a function to refresh the desktop like pressing "F5" does. I found many codes with Sendmessage and ToggleDesktopIcons on/off but none worked for me like manual hit of "F5" does. I saw also some topics here, but all with non-working solutions for this matter. I am on Windows 7 64 Bit with IE 10 and use C# Net Framework 2.

I found also this code, but C# doesn't accept it, even if it seems to me as the right function. I dunno what I need to change here. I would expect that the IDE would tell me what is my mistake here or what I need to correct. Can someone please correct me this function or suggest another function which is compatible to C#.

procedure RefreshDesktop2;
var
hDesktop: HWND;
begin
hDesktop := FindWindowEx(FindWindowEx(FindWindow('Progman', 'Program Manager'), 0,
 'SHELLDLL_DefView', ''), 0, 'SysListView32', '');
 PostMessage(hDesktop, WM_KEYDOWN, VK_F5, 0);
 PostMessage(hDesktop, WM_KEYUP, VK_F5, 1 shl 31);
end; 

Question: How do I make the code above working in C# (translate in C#) or how looks a similar code in C# like. Refreshing the desktop with its icons/settings like by pressing "F5" on a selected desktop icon is my goal. Several codes which I tried in similar questions brought me no result.

1

There are 1 answers

0
King King On BEST ANSWER

OK, I don't really understand your code, in fact you have to find the exact window to send the F5 keypress to it so that it will refresh the desktop. Here is the c# code (tested and worked like a charm:)

[DllImport("user32")]
private static extern int PostMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32")]
private static extern IntPtr FindWindow(string className, string caption);
[DllImport("user32")]
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr startChild, string className, string caption);
public void RefreshDesktop(){      
  IntPtr d = FindWindow("Progman", "Program Manager");
  d = FindWindowEx(d, IntPtr.Zero, "SHELLDLL_DefView", null);
  d = FindWindowEx(d, IntPtr.Zero, "SysListView32", null);      
  PostMessage(d, 0x100, new IntPtr(0x74), IntPtr.Zero);//WM_KEYDOWN = 0x100  VK_F5 = 0x74
  PostMessage(d, 0x101, new IntPtr(0x74), new IntPtr(1 << 31));//WM_KEYUP = 0x101
}

However I think there are still other choices for you to refresh the desktop programmatically, here is one of the links How to refresh the windows desktop programmatically (i.e. F5) from C#?