#include <windows.h>   

#include "typbrows.h"
#include "resource.h"


#define notifyMsg HIWORD(wParam)
unsigned long dwIndex;
HWND hMainWnd ;
extern HINSTANCE hInst ;


LPTYPELIB pTypeLib  ;

BOOL CALLBACK TypeBrowseProc (HWND hDlg,UINT message,	WPARAM wParam,	LPARAM lParam)
{

	switch(message)
	{  
	                
		case WM_INITDIALOG:
		{
			pTypeLib = (LPTYPELIB) lParam ;
			
			pTypeLib->AddRef( ) ;
			InitTypeLib (pTypeLib, hDlg) ;

			ShowWindow (hDlg, SW_SHOWNORMAL) ;

			return TRUE ;
		}
		
		case WM_COMMAND:
		{
	 	  	switch(LOWORD(wParam))
		  	{
				case IDCANCEL:
				{
					SendMessage (hDlg, WM_CLOSE, 0, 0) ;
					return TRUE ;
				}
/*
The selection changes on the type list and we have to update the member 
list & type info.
*/
		  		case IDC_TYPELIST:        
		  		{
					if(notifyMsg == LBN_SELCHANGE)
					{
			  			dwIndex = SendDlgItemMessage(hDlg, IDC_TYPELIST, LB_GETCURSEL, 0, 0L);
			  			if(dwIndex != LB_ERR)
			  			{
							SetSelectedType(pTypeLib, dwIndex, hDlg);
						}
					}
					else if (notifyMsg == LBN_DBLCLK)
					{
						SendMessage (hDlg, WM_COMMAND, IDC_BUTTON2, 0) ;
					}
					break;
				}
				
/*
User clicked "Open Type Info" button.  Get the selected type info and
open it.  Pop up the dialog in which typeinfos are displayed.
*/
				case IDC_BUTTON2:
				{
					LPTYPEINFO pTypeInfo ;
					HRESULT hr ;

		  			LRESULT lr = SendDlgItemMessage (hDlg, IDC_TYPELIST, LB_GETCURSEL, 0, 0L) ;					
/*
STEP 7
Use the method ITypeLib::GetTypeInfo( ) to open the type library.  					
The index of the type info is the same as the index of the list box, 
which you will find the the variable "lr".Store the pointer in the variable 
"pTypeInfo". 
*/


   				 	if (!SUCCEEDED(hr))
    				{
    					MessageBox (NULL, TEXT("Couldn't open type info"), TEXT("Error"), 0) ;
    				}
    				else
					{
						CreateDialogParam (hInst, MAKEINTRESOURCE(IDD_DIALOG2), hDlg ,
							(DLGPROC)TypeInfoDlgProc , (LPARAM)pTypeInfo) ;
						pTypeInfo->Release( ) ;
					}
					break ;
				}                   
				case ID_DOHELP:
				{
					OLECHAR HelpFileName [128], HelpContextName [128] ; 
					long HelpContext ;
					
					GetDlgItemText (hDlg, IDC_HELPFILE, HelpFileName, sizeof(HelpFileName)) ;
					GetDlgItemText (hDlg, IDC_HELPCONTEXT, HelpContextName, sizeof(HelpContextName)) ;				
					
					HelpContext = _wtol (HelpContextName) ;
				    WinHelp (hDlg, HelpFileName, HELP_CONTEXT, HelpContext) ;
					break ;
				}
			}	
	  		return TRUE ;       
	  	}

		case WM_CLOSE:
		{
			pTypeLib->Release( ) ;
			DestroyWindow (hDlg) ;
			return TRUE ;
		}
	}
	
	return FALSE ;
}
