Processing HTML Forms From a CHtmlView






4.59/5 (11 votes)
A simple method to processing HTML forms From a CHtmlView
Introduction
In my wanderings I have seen a lot of code to get HTML dialogs, html pages and the like into a C++ project but I haven't heard any mention about processing forms. That is about to end now, the included project demonstrates (very basic) processing of information submitted by a HTML form (which loaded from the application's resources).
The project also demonstrates the use of linked HTML pages within the application's resources. While I did not specifically demonstrate it's use, JavaScript and/or VBScript can be used as well. The possibility of using Java class files has also come to mind, but that is beyond the scope of this article.
The project overrides CHtmlView::OnBeforeNavigate2
to catch the form data. The only way to get this navigation message from the CHtmlView
is to simply place an action property in the <FORM>
tag like this:
<FORM action="" method="POST" name="Test">
The overridden code is as follows:
void CTestHTMLView::OnBeforeNavigate2(LPCTSTR lpszURL, DWORD nFlags, LPCTSTR lpszTargetFrameName, CByteArray& baPostedData, LPCTSTR lpszHeaders, BOOL* pbCancel) { // Are we on the initial navigation thrown by the // OnInitialUpdate? If not, process the POST. if( m_bProcessNavigate ) { // Build a message box from the submitted data CString strMessage, strBytes; strMessage = _T(""); // Get general info from the submitted form strMessage.Format( _T("Browse To:\n%s\n\nFlags: %d\nTarget Frame:\n%s\n\nHeaders:\n%s\n"), lpszURL, nFlags, lpszTargetFrameName, lpszHeaders); // Get the POST data // This is where this sample gets semi-cool strBytes = _T("\n\nPosted Bytes :\n\n"); if (baPostedData.GetSize()) { // This is a kludgy copy, but you get the idea for(int i = 0;i < baPostedData.GetSize();i++) { strBytes += (char)baPostedData[i]; } // Let's split the posted data into separate lines // for the messagebox strBytes.Replace("&","\n"); } // Once the data is copied, we can do anything we // want with it, but I'll just display the silly // MessageBox AfxMessageBox((strMessage + strBytes),MB_OK); // Let's NOT Navigate! //*pbCancel = TRUE; } CHtmlView::OnBeforeNavigate2(lpszURL, nFlags, lpszTargetFrameName, baPostedData, lpszHeaders, pbCancel); }
Try the program, have a good look at the source for both the C++ and HTML, I have tried to make sure everything I did is fully documented.
Enjoy!