I have the following code which finds a window by a partial name given..
I've tested it and it doesnt work in Dev c++ but it definitely works in visual studio 2008.. So I decided to make a form with nothing on it and implement this code to see if it will work.. The code is below and below that is my attempt.

#include <Windows.h>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct FindWindowData{
    FindWindowData(TCHAR const * windowTitle)
        : WindowTitle(windowTitle)
        , ResultHandle(0)
    {}

    std::basic_string<TCHAR> WindowTitle;
    HWND ResultHandle;
};

BOOL CALLBACK FindWindowImpl(HWND hWnd, LPARAM lParam){
    FindWindowData * p = reinterpret_cast<FindWindowData*>(LongToPtr(lParam));
    if(!p) {
        // Finish enumerating we received an invalid parameter
        return FALSE;
    }

    int length = GetWindowTextLength(hWnd) + 1;
    if(length > 0) {
        std::vector<TCHAR> buffer(std::size_t( length), 0);      
        if(GetWindowText(hWnd, &buffer[0], length)) {
                    // Comparing the string - If you want to add some features you can do it here
            if(_strnicmp(&buffer[0], p->WindowTitle.c_str(), min(buffer.size(), p->WindowTitle.size())) == 0){
                p->ResultHandle = hWnd;
                // Finish enumerating we found what we need
                return FALSE;
            }
        }
    }
    // Continue enumerating
    return TRUE;
}

// Returns the window handle when found if it returns 0 GetLastError() will return more information
HWND FindWindowStart(TCHAR const * windowTitle){

    if(!windowTitle){
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

    FindWindowData data(windowTitle);
    if( !EnumWindows(FindWindowImpl, PtrToLong(&data)) && data.ResultHandle != 0){
        SetLastError(ERROR_SUCCESS);
        return data.ResultHandle;
    }

    // Return ERROR_FILE_NOT_FOUND in GetLastError
    SetLastError(ERROR_FILE_NOT_FOUND);
    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << "HWND: " << FindWindowStart(TEXT("foobar "));
    std::cout << "GetLastError() = " << GetLastError() << std::endl;
    return 0;
}

My Attempt which failed with 1 Error!! =( :

#pragma once
#include <Windows.h>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct FindWindowData{
    FindWindowData(TCHAR const * windowTitle)
        : WindowTitle(windowTitle)
        , ResultHandle(0)
    {}

    std::basic_string<TCHAR> WindowTitle;
    HWND ResultHandle;
};


namespace FindWindowEnum {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;

	/// <summary>
	/// Summary for Form1
	///
	/// WARNING: If you change the name of this class, you will need to change the
	///          'Resource File Name' property for the managed resource compiler tool
	///          associated with all .resx files this class depends on.  Otherwise,
	///          the designers will not be able to interact properly with localized
	///          resources associated with this form.
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
			//
			//TODO: Add the constructor code here
			//
		}

	protected:
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}

	private:
		/// <summary>
		/// Required designer variable.
		/// </summary>
		System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		void InitializeComponent(void)
		{
			this->SuspendLayout();
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(284, 262);
			this->Name = L"Form1";
			this->Text = L"Form1";
			this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
			this->ResumeLayout(false);

		}
#pragma endregion

BOOL CALLBACK FindWindowImpl(HWND hWnd, LPARAM lParam){
    FindWindowData * p = reinterpret_cast<FindWindowData*>(LongToPtr(lParam));
    if(!p) {
        // Finish enumerating we received an invalid parameter
        return FALSE;
    }

    int length = GetWindowTextLength(hWnd) + 1;
    if(length > 0) {
        std::vector<TCHAR> buffer(std::size_t( length), 0);      
        if(GetWindowText(hWnd, &buffer[0], length)) {
                    // Comparing the string - If you want to add some features you can do it here
            if(_strnicmp(&buffer[0], p->WindowTitle.c_str(), min(buffer.size(), p->WindowTitle.size())) == 0){
                p->ResultHandle = hWnd;
                // Finish enumerating we found what we need
                return FALSE;
            }
        }
    }
    // Continue enumerating
    return TRUE;
}

// Returns the window handle when found if it returns 0 GetLastError() will return more information
HWND FindWindowStart(TCHAR const * windowTitle){

    if(!windowTitle){
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

    FindWindowData data(windowTitle);
    if( !EnumWindows(FindWindowImpl, PtrToLong(&data)) && data.ResultHandle != 0){
        SetLastError(ERROR_SUCCESS);
        return data.ResultHandle;
    }

    // Return ERROR_FILE_NOT_FOUND in GetLastError
    SetLastError(ERROR_FILE_NOT_FOUND);
    return 0;
}
	private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
			 }
	};
}

Can anyone help me?? I've never had to convert before but this time I have no other choice =(

And no I don't want to alloc a console and do this.. I want it to run without a console that why I wanted a form.

Edited 5 Years Ago by triumphost: Damn.. I just realize I put a stupid title :(

*Sigh* six hours straight... not a single person knows how :S

I tried delegate BOOL FindWindowImpl(HWND hWnd, LPARAM lParam);
but I still cant get it to run :S..

No one has answered because you have posted almost 200 lines of code without a definitive question and no really explanation of what is wrong.

Well I thought the title explains it? And the two different kinds of code..

I have a the first set of code which works for CONSOLE apps. I want to implement that Code into my .Net application (the second set).

The second set of code is my attempt at doing it but failing. There is no definitive problem other than it wont work because it isn't C++ managed code.

I have tried Delegate Callback but it didnt work and most likely im doing it wrong.

So my question is: How do I implement the first set of code(unmanaged) into the second set(managed)?

Depending on what you are actually going to do with the .NET code, you can relax the compilation from /CLR:pure setting to just /CLR (within the project propeties) and see if the two will play along.

The unmanaged code is not called CLR, by the way. The CLR is the runtime for the managed code. I'd probably call the first part Win32 API and/or native code.

Depending on what you are actually going to do with the .NET code, you can relax the compilation from /CLR:pure setting to just /CLR (within the project propeties) and see if the two will play along.

The unmanaged code is not called CLR, by the way. The CLR is the runtime for the managed code. I'd probably call the first part Win32 API and/or native code.

Well its just a form and basically All I want to do is take the text from a textbox, pass it to the FindWindowStart and then display a messagebox if its found.

I've been trying this for a couple days now but it seems impossible..

I've just came up with this a few minutes ago but it still fails so badly :(

delegate bool WindowFinder(HWND hwnd, LPARAM lParam);       //MY ATTEMPT AT THE DELEGATE

struct FindWindowData{
    FindWindowData(TCHAR const * windowTitle)               //The Struct
        : WindowTitle(windowTitle)
        , ResultHandle(0)
    {}

    std::basic_string<TCHAR> WindowTitle;
    HWND ResultHandle;
};

	ref class WndFind                                            //The Class
	{
	public:
		[DllImport("user32")]
		static int EnumWindows(WindowFinder^ x, LPARAM lParam);

		static void Main()                                               //THIS IS WHERE IM LOST!
		{
			WndFind^ New = gcnew WndFind;
			WindowFinder^ WndFoundCallBack = gcnew WindowFinder(&WndFind::FoundWnd);
			EnumWindows(WndFoundCallBack, 0);
		}

		static bool FoundWnd(HWND hwnd, LPARAM lParam)                      //THE CALLBACK
		{
		    FindWindowData * p = reinterpret_cast<FindWindowData*>(LongToPtr(lParam));
			if(!p) {
        // Finish enumerating we received an invalid parameter
			return false;
			}

			int length = GetWindowTextLength(hwnd) + 1;
			if(length > 0) {
			std::vector<TCHAR> buffer(std::size_t( length), 0);      
			if(GetWindowText(hwnd, &buffer[0], length)) {
                    // Comparing the string - If you want to add some features you can do it here
            if(_strnicmp(&buffer[0], p->WindowTitle.c_str(), min(buffer.size(), p->WindowTitle.size())) == 0){
                p->ResultHandle = hwnd;
                // Finish enumerating we found what we need
                return false;
					}
				}
			}
			// Continue enumerating
			return true;
		}

	HWND FindWindowStart(TCHAR const * windowTitle){                          //DECLARE FindWindowStart
    if(!windowTitle){
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

    FindWindowData data(windowTitle);
	if(!EnumWindows((WNDENUMPROC)FoundWnd, PtrToLong(&data)) && data.ResultHandle != 0){
        SetLastError(ERROR_SUCCESS);
        return data.ResultHandle;
    }

    // Return ERROR_FILE_NOT_FOUND in GetLastError
    SetLastError(ERROR_FILE_NOT_FOUND);
    return 0;
  }
};

//and for the code for my button I have:

WndFind::FindWindowStart(TEXT("foobar "));                                     //USE THIS IN MY BUTTON CLICK EVENT

Edited 5 Years Ago by triumphost: n/a

I have no idea what might be wrong with your code, to be honest.

Try looking into http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx the Process class. I think you'll find there's quite a bit there that will help you, and you won't have to mix the managed and unmanaged code as much.

Aww damn :( Thanks for being honest though and taking the time to reply.
I looked at your link but its not exactly what I wanted to do. Didnt wanna start a process..

Basically what I tried to do above was find a window by partial title. and ancient dragon told me to Enum all windows..
I tried that and came up with the following below but couldnt find out how to let the user enter the name of the window or how to find out if the window is found.. Below code is compilable and works but I cant let the user choose the name of the window thats y i made the post above to try and alter the following which failed bad and obviously if u dont know how to do what im trying to do then Im badly off..

#pragma once
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "user32.lib")

#include <Windows.h>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

namespace Hmm {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;
	using namespace System::Runtime::InteropServices;

	delegate bool WindowFinder(HWND hwnd, LPARAM lParam);


	/// <summary>
	/// Summary for Form1
	///
	/// WARNING: If you change the name of this class, you will need to change the
	///          'Resource File Name' property for the managed resource compiler tool
	///          associated with all .resx files this class depends on.  Otherwise,
	///          the designers will not be able to interact properly with localized
	///          resources associated with this form.
	/// </summary>

ref class WndFind
{
// Report the window handle.
public:
    [DllImport("user32")]
    static int EnumWindows(WindowFinder^ x, LPARAM lParam);
    
    static void Main()
    {
        WndFind^ hWnd = gcnew WndFind;
        WindowFinder^ WndFoundCallBack = gcnew WindowFinder(&WndFind::FoundWnd);
        EnumWindows(WndFoundCallBack, 0);
    }

    static bool FoundWnd(HWND hwnd, LPARAM lParam)
    {
		static TCHAR buffer[50];
        GetWindowText(hwnd, buffer, 50);
		if(strstr(buffer, "Public")) {
			SetForegroundWindow(hwnd);
			MessageBox::Show("Found");
        return FALSE;
		}
		return TRUE;
    }
};

	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
			//
			//TODO: Add the constructor code here
			//
		}

	protected:
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}
	private: System::Windows::Forms::Button^  button1;
	protected: 

	private:
		/// <summary>
		/// Required designer variable.
		/// </summary>
		System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		void InitializeComponent(void)
		{
			this->button1 = (gcnew System::Windows::Forms::Button());
			this->SuspendLayout();
			// 
			// button1
			// 
			this->button1->Location = System::Drawing::Point(124, 114);
			this->button1->Name = L"button1";
			this->button1->Size = System::Drawing::Size(75, 23);
			this->button1->TabIndex = 0;
			this->button1->Text = L"button1";
			this->button1->UseVisualStyleBackColor = true;
			this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(284, 262);
			this->Controls->Add(this->button1);
			this->Name = L"Form1";
			this->Text = L"Form1";
			this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
			this->ResumeLayout(false);

		}
#pragma endregion

	private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
			 }
	private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
				 WndFind::Main();
			 }
	};
}
This article has been dead for over six months. Start a new discussion instead.