Search code examples
c#winformshwnd

hwnd window handle problem in saving file in different locations


New to windows forms/window handle.

Trying to save files in different locations.

SaveFileDialog Image:

enter image description here

I am able to get the edit box handle of the file name edit boxes in save file dialog. Able to paste the path.

enter image description here

private const int WM_SETTEXT = 0x000C;

IntPtr edithWnd = IntPtr.Zero;
edithWnd = FindWindowEx(edithWnd, IntPtr.Zero, "Edit", null);
SendMessage(edithWnd, WM_SETTEXT, IntPtr.Zero, "D:\Mine\Folder1\file");

Above code sets file path in file name text box.

Now, Clicking the "Save" button by getting its handle and sending a click.

private const int BM_CLICK = 0x00F5;

IntPtr handle = GetForegroundWindow(); // Save As dialog
IntPtr edithWnd = FindWindowEx(handle, IntPtr.Zero, "Button", "&Save");           
SendMessage(edithWnd, BM_CLICK, IntPtr.Zero, null);

It's working fine, but while using this code in the loop for multiple files to save in different locations, it's not working properly, it is saving all the files in one location only

For eg, file is saved in "D:\Mine\Folder1\file"

file1 is not being saved in "D:\Mine\Folder2\file1" instead it is being saved in "D:\Mine\Folder1\file1"

file2 is not being saved in "D:\Mine\Folder3\file2" instead it is being saved in "D:\Mine\Folder1\file2"

Seems like it is pointing to the first location only, no matter what the path is.


Solution

  • Why not to get into the desired path first and then save the file.

    Worked for me..

    SendMessage(edithWnd, WM_SETTEXT, IntPtr.Zero, "D:\Mine\Folder1\");
    // Hit enter
    SendKeys.SendWait("{ENTER}");
    // Now click the save button, file name will be there already, in case if it is 
    // not paste the file name first and then perform save button click
    

    You might need to focus the file path before pressing "Enter" that will set the focus and pressing "Enter" will let you inside your folder path.