Reporte Ejercicios
Visual Studio
Programacin Avanzada
Objetivo
Desarrollar habilidades en la programacin de objetos mediante la realizacin de los ejercicios propuestos en el
documento Teach Yourself Visual C++ in 21 Days, en los que manejaremos las herramientas del software Microsoft
Visual Studio para C++.
Marco Terico
Visual Studio es un conjunto completo de herramientas de desarrollo para la generacin de aplicaciones web
ASP.NET, Servicios Web XML, aplicaciones de escritorio y aplicaciones mviles. Visual Basic, C# y C++ utilizan todos el
mismo entorno de desarrollo integrado (IDE) que habilita el uso compartido de herramientas y hace ms sencilla la
creacin de soluciones en varios lenguajes. As mismo, dichos lenguajes utilizan las funciones de .NET Framework, las
cuales ofrecen acceso a tecnologas clave para simplificar el desarrollo de aplicaciones web ASP y Servicios Web XML.
Retomando Visual C++, incluye las MFC (Microsoft Foundation Classes), que son clases que facilitan la
programacin Windows, sin tener que usar directamente el API de dicho sistema, pues agrupan las libreras de Windows
en clases C++. Fueron introducidas por Microsoft en 1992 y desde entonces fueron apareciendo nuevas versiones con
las actualizaciones del entorno de programacin Visual C++. MFC es una jerarqua de estas clases, y nos proporciona un
modelo de desarrollo de aplicaciones llamado documento/vista, que nos permite disear aplicaciones de forma que
los datos de la aplicacin vayan separados de los elementos que componen el interfaz de usuario, lo que permite
modificar de forma independiente las dos partes del programa.
Adems, MFC brinda la oportunidad de crear controles ActiveX, que son un componente de software
reutilizable, basado en el modelo de objetos componentes (COM), que admite una gran variedad de funciones OLE y se
puede personalizar de modo que se adapte a las necesidades del software. Estos controles estn diseados para su uso
tanto en contenedores de controles ActiveX ordinarios como en pginas Web de Internet. Se pueden desarrollar para
muchos usos, tales como acceso a bases de datos, supervisin de datos o creacin de grficos.
Desarrollo
Da 1. Creando tu primer aplicacin C++
En este ejercicio nos muestra paso a paso como iniciar nuestra primera aplicacin y comenzar a familiarizarnos con el
programa. Consta de dos botones, Ok y Cancel con los que aparecer un mensaje o finalizar la aplicacin
respectivamente.
BOTN OK (MUESTRA UN MENSAJE)
MessageBox(_T("Mi primer app en Visual C++"));
CUADRO DE EDICIN
BOOL CDay2Dlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
m_strMessage = "Escribe algo aqu...";
m_bShowMsg = TRUE;
m_bShowPgm = TRUE;
m_bEnableMsg = TRUE;
m_bEnablePgm = TRUE;
UpdateData(FALSE);
return TRUE; // return TRUE
BOTN DE SALIDA
void CDay2Dlg::OnClickedExit()
{
// TODO: Add your control notification handler code here
OnOK();
}
MOSTRAR MENSAJE
void CDay2Dlg::OnBnClickedShwmsg()
{
UpdateData(TRUE);
MessageBox(m_strMessage);
// TODO: Add your control notification handler code here
}
ELIMINAR MENSAJE
void CDay2Dlg::OnBnClickedClrmsg()
{
m_strMessage = "";
UpdateData(FALSE);
// TODO: Add your control notification handler code here
}
{
b_Line = 8;
}
if (lsChar == '4')
{
b_Line = 16;
}
if (lsChar == '5')
{
b_Line = 36;
}
if (lsChar == '6')
{
b_Colors = RGB(0,0,0);
}
if (lsChar == '7')
{
b_Colors = RGB(255,128,0);
}
if (lsChar == '8')
{
b_Colors = RGB(0,128,255);
}
if (lsChar == '9')
{
b_Colors = RGB(0,153,0);
}
if (lsChar == '0')
{
b_Colors = RGB(127,0,204);
}
if (lsChar == 'A')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_ARROW);
SetCursor(lhCursor);
}
if (lsChar == 'B')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_IBEAM);
SetCursor(lhCursor);
}
if (lsChar == 'C')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_WAIT);
SetCursor(lhCursor);
}
if (lsChar == 'D')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_NO);
SetCursor(lhCursor);
}
if (lsChar == 'E')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_CROSS);
SetCursor(lhCursor);
}
if (lsChar == 'F')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_HELP);
SetCursor(lhCursor);
}
if (lsChar == 'G')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_SIZEALL);
SetCursor(lhCursor);
}
if (lsChar == 'H')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_UPARROW);
SetCursor(lhCursor);
}
if (lsChar == 'I')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_SIZENWSE);
SetCursor(lhCursor);
}
if (lsChar == 'J')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_SIZENESW);
SetCursor(lhCursor);
}
if (lsChar == 'K')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_SIZEWE);
SetCursor(lhCursor);
}
if (lsChar == 'L')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_SIZENS);
SetCursor(lhCursor);
}
if (lsChar == 'M')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_HAND);
SetCursor(lhCursor);
}
if (lsChar == 'N')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_APPSTARTING);
SetCursor(lhCursor);
}
if (lsChar == 'X')
{
lhCursor = AfxGetApp() -> LoadStandardCursor(IDC_ARROW);
m_bCursor = TRUE;
SetCursor(lhCursor);
OnOK();
}
else
{
m_bCursor = TRUE;
}
UpdateData (FALSE);
CDialogEx::OnKeyDown(nChar, nRepCnt,
nFlags);
}
INICIAR CONTADOR
void CTimerDlg::OnBnClickedStartime()
{
UpdateData(TRUE);
m_iCount = 0;
m_sCount.Format("%d",m_iCount);
UpdateData(FALSE);
SetTimer(ID_COUNT_TIMER, m_iInterval, NULL);
m_cStopTime.EnableWindow(TRUE);
m_cButton.EnableWindow(FALSE);
m_cStartTime.EnableWindow(FALSE);
}
DETENER CONTADOR
void CTimerDlg::OnBnClickedStoptime()
{
KillTimer(ID_COUNT_TIMER);
m_cStopTime.EnableWindow(FALSE);
m_cButton.EnableWindow(TRUE);
m_cStartTime.EnableWindow(TRUE);
// TODO: Add your control notification handler code here
}
Da 6. Creando Mens
El uso de mens es una parte importante en una aplicacin, por ello en este ejercicio hacemos uso de estos. Agregamos
una barra con mens desplegables y uno ms tras presionar el botn derecho del ratn, en el cul se posiciono dicho
men de tal forma que una de las esquinas del mismo, coincidiera con la punta del cursor.
OPCIN HELLO DEL MEN FILE
void CMenusDlg::OnFileHello()
{
// TODO: Add your command handler code here
MessageBox(L"Hello World", L"Hello");
}
// return TRUE
FUENTE AL TEXTO
void CDay7Dlg::OnLbnSelchangeLfonts()
{
// TODO: Add your control notification handler code here
// Update the variables with the dialog controls
UpdateData(TRUE);
if (!m_bUseText)
{
// Copy the font name to the font sample
m_strDisplayText = m_strFontName;
// Update the dialog with the variables
UpdateData(FALSE);
}
// Set the font for the sample
SetMyFont();
}
FUNCIN SETMYFONT
void CDay7Dlg::SetMyFont(void)
{
CRect rRect; // The rectangle of the display area
int iHeight; // The height of the display area
int iItalic=0;
int iUnderline=0;
int iStrike=0;
// Has a font been selected?
if (m_strFontName != "")
{
// Get the dimensions of the font sample display area
m_ctlDisplayText.GetWindowRect(&rRect);
// Calculate the area height
iHeight = rRect.top - rRect.bottom;
// Make sure the height is positive
if (iHeight < 0)
iHeight = 0 - iHeight;
m_fSampFont.Detach();
// Should the font be italicized?
if (m_bItalic)
iItalic = 1;
if (m_bDefault)
iUnderline = 1;
}
else
{
// Get the dimensions of the font sample display area
m_ctlDisplayText.GetWindowRect(&rRect);
// Calculate the area height
iHeight = rRect.top - rRect.bottom;
// Make sure the height is positive
if (iHeight < 0)
iHeight = 0 - iHeight;
m_fSampFont.Detach();
// Create the font to be used
m_fSampFont.CreateFont((iHeight - 5), 0, 0, 0, FW_NORMAL,0, 0, 0, DEFAULT_CHARSET,
OUT_CHARACTER_PRECIS,CLIP_CHARACTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH |FF_DONTCARE,
m_strFontName);
}
}
FUNCIN FILLFONTLIST
void CDay7Dlg::FillFontList()
{
int iCount; // The number of fonts
int iCurCount; // The current font
CString strCurFont; // The current font name
CString strPrevFont = L""; // The previous font name
LOGFONT lf;
// Initialize the LOGFONT structure
lf.lfCharSet = DEFAULT_CHARSET;
strcpy_s(lf.lfFaceName, L"");
// Clear the list box
m_ctlFontList.ResetContent();
// Create a device context variable
CClientDC dc (this);
// Enumerate the font families
::EnumFontFamiliesEx((HDC) dc, &lf,(FONTENUMPROC) EnumFontFamProc, (LPARAM) this, 0);
// Get the number of fonts in the list box
iCount = m_ctlFontList.GetCount();
// Loop from the last entry in the list box to the first,
// searching for and deleting the duplicate entries
for (iCurCount = iCount; iCurCount > 0; iCurCount--)
{
// Get the current font name
m_ctlFontList.GetText((iCurCount - 1), strCurFont);
// Is it the same as the previous font name?
if (strCurFont == strPrevFont)
{
// If yes, then delete it
m_ctlFontList.DeleteString((iCurCount - 1));
}
// Set the previous font name to the current font name
strPrevFont = strCurFont;
}
}
Da 8. Agregando Flash
Sin duda un ejercicio en el que ponemos a prueba lo aprendido, esto porque las instrucciones se tornan menos
descriptivas. Sin ms prembulo, esta aplicacin consiste en dibujar grficos al seleccionar en una ventana el formato,
mientras en otra apreciamos el resultado tras actualizar la aplicacin.
MOSTRAR VENTANA PARA TRAZOS
BOOL CGraphicsDlg::OnInitDialog()
{
m_iColor = 0;
m_iShape = 0;
m_iTool = 0;
UpdateData(FALSE);
m_dlgPaint.Create(IDD_PAINT_DLG, this);
m_dlgPaint.ShowWindow(SW_SHOW);
return TRUE;
// Devuelve TRUE
BOTN ACTUALIZAR
void CGraphicsDlg::OnActualizar()
{
// TODO: Agregue aqu su cdigo de controlador de notificacin de control
UpdateData(TRUE);
m_dlgPaint.Invalidate();
}
BOTN BITMAP
void CGraphicsDlg::OnBbitmap()
{
// TODO: Agregue aqu su cdigo de controlador de notificacin de control
static char BASED_CODE szFilter[] = "Bitmap Files (*.bmp)|*.bmp||";
CFileDialog m_ldFile(TRUE, ".bmp", m_sBitmap,
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter);
if (m_ldFile.DoModal() == IDOK)
{
m_sBitmap = m_ldFile.GetPathName();
HBITMAP hBitmap = (HBITMAP) ::LoadImageA (AfxGetInstanceHandle(),
m_sBitmap, IMAGE_BITMAP, 0, 0,
LR_LOADFROMFILE | LR_CREATEDIBSECTION);
if (hBitmap)
{
if (m_bmpBitmap.DeleteObject())
m_bmpBitmap.Detach();
m_bmpBitmap.Attach(hBitmap);
}
m_dlgPaint.Invalidate();
}
}
TABLA DE COLORES
const COLORREF CPaintDlg::m_crColors[8] = {
RGB( 0, 0, 0),
RGB( 0, 0, 255),
RGB( 0, 255, 0),
RGB( 0, 255, 0),
RGB( 255, 0, 0),
RGB(255, 0, 255),
RGB(255, 255, 0),
RGB(255, 255, 255)
};
FUNCIN DRWALINE
void CPaintDlg::DrawLine(CPaintDC *pdc, int iColor)
{
CPen lSolidPen (PS_SOLID, 1, m_crColors[iColor]);
CPen lDotPen (PS_DOT, 1, m_crColors[iColor]);
CPen lDashPen (PS_DASH, 1, m_crColors[iColor]);
CPen lDashDotPen (PS_DASHDOT, 1, m_crColors[iColor]);
CPen lDashDotDotPen (PS_DASHDOTDOT, 1, m_crColors[iColor]);
CPen lNullPen (PS_NULL, 1, m_crColors[iColor]);
CPen lInsidePen (PS_INSIDEFRAME, 1, m_crColors[iColor]);
CRect lRect;
GetClientRect (lRect);
lRect.NormalizeRect();
CPoint pStart;
CPoint pEnd;
int liDist = lRect.Height() / 8;
CPen *lOldPen;
pStart.y
pStart.x
pEnd.y =
pEnd.x =
= lRect.top;
= lRect.left;
pStart.y;
lRect.right;
int i;
for (i=0; i<7; i++)
{
switch (i)
{
case 0:
lOldPen = pdc->SelectObject(&lSolidPen);
break;
case 1:
pdc->SelectObject(&lDotPen);
break;
case 2:
pdc->SelectObject(&lDashPen);
break;
case 3:
pdc->SelectObject(&lDashDotPen);
break;
case 4:
pdc->SelectObject(&lDashDotDotPen);
break;
case 5:
pdc->SelectObject(&lNullPen);
break;
case 6:
pdc->SelectObject(&lInsidePen);
break;
}
pStart.y = pStart.y + liDist;
pEnd.y = pStart.y;
pdc->MoveTo(pStart);
pdc->LineTo(pEnd);
}
pdc->SelectObject(lOldPen);
}
FUNCIN ONPAINT
void CPaintDlg::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Agregue aqu su cdigo de controlador de mensajes
CGraphicsDlg *pWnd = (CGraphicsDlg*) GetParent();
if(pWnd)
{
if (pWnd->m_iTool == 2)
{
if (pWnd->m_sBitmap != "")
ShowBitmap(&dc, pWnd);
}
else
{
if (pWnd->m_iShape == 0)
DrawLine(&dc, pWnd->m_iColor);
else
DrawRegion(&dc, pWnd->m_iColor, pWnd->m_iTool, pWnd->m_iShape);
}
}
// No llama a CDialog::OnPaint() para mensajes de pintura
}
FUNCIN DRAWREGION
void CPaintDlg::DrawRegion(CPaintDC *pdc, int iColor, int iTool, int iShape)
{
CPen lSolidPen (PS_SOLID, 1, m_crColors[iColor]);
CPen lDotPen (PS_DOT, 1, m_crColors[iColor]);
CPen lDashPen (PS_DASH, 1, m_crColors[iColor]);
CPen lDashDotPen (PS_DASHDOT, 1, m_crColors[iColor]);
CPen lDashDotDotPen (PS_DASHDOTDOT, 1, m_crColors[iColor]);
CPen lNullPen (PS_NULL, 1, m_crColors[iColor]);
CPen lInsidePen (PS_INSIDEFRAME, 1, m_crColors[iColor]);
CBrush
CBrush
CBrush
CBrush
CBrush
CBrush
CBrush
CBrush
lSolidBrush (m_crColors[iColor]);
lBDiagBrush (HS_BDIAGONAL, m_crColors[iColor]);
lCrossBrush (HS_CROSS, m_crColors[iColor]);
lDiagCrossBrush (HS_DIAGCROSS, m_crColors[iColor]);
lFDiagBrush (HS_FDIAGONAL, m_crColors[iColor]);
lHorizBrush (HS_HORIZONTAL, m_crColors[iColor]);
lVertBrush (HS_VERTICAL, m_crColors[iColor]);
lNullBrush (RGB(192, 192, 192));
CRect lRect;
GetClientRect (lRect);
lRect.NormalizeRect();
int liVert = lRect.Height() / 2;
int liHeight = liVert - 10;
}
if (iTool == 0)
pdc->SelectObject(lNullBrush);
else
pdc->SelectObject(lNullPen);
if (iShape == 1)
pdc->Ellipse(lDrawRect);
else
pdc->Rectangle(lDrawRect);
}
pdc->SelectObject(lOldBrush);
pdc->SelectObject(lOldPen);
}
Da 9. Agregando Active X
En este ltimo ejercicio utilizamos un control Active X, que previamente debimos habilitarlo en el sistema para poder
hacer uso de l. Este control, no es ms que una tabla en la que mostramos datos aleatorios.
FUNCIN LOADDATA
void CActiveXDlg::LoadData(void)
{
int liCount;
CString lsAmount;
srand((unsigned)time(NULL));
for (liCount = m_ctlFGrid.get_FixedRows();
liCount < m_ctlFGrid.get_Rows(); liCount++)
{
m_ctlFGrid.put_TextArray(GenID(liCount, 0),
m_ctlFGrid.put_TextArray(GenID(liCount, 1),
m_ctlFGrid.put_TextArray(GenID(liCount, 2),
lsAmount.Format("%5d.00", rand());
m_ctlFGrid.put_TextArray(GenID(liCount, 3),
}
m_ctlFGrid.put_MergeCol(0, TRUE);
m_ctlFGrid.put_MergeCol(1, TRUE);
m_ctlFGrid.put_MergeCol(2, TRUE);
DoSort();
}
RandomStringValue(0));
RandomStringValue(1));
RandomStringValue(2));
lsAmount);
FUNCIN GENID
int CActiveXDlg::GenID(int m_iRow, int m_iCol)
{
int liCols = m_ctlFGrid.get_Cols();
return (m_iCol + liCols * m_iRow);
return 0;
}
VALOR ALEATORIO
CString CActiveXDlg::RandomStringValue(int m_iColumn)
{
CString lsStr;
int liCase;
switch (m_iColumn)
{
case 0:
liCase = (rand() % 5);
switch (liCase)
{
case 0:
lsStr = "Northwest";
break;
case 1:
lsStr = "Southwest";
break;
case 2:
lsStr = "Midwest";
break;
case 3:
lsStr = "Northeast";
break;
default:
lsStr = "Southeast";
break;
}
break;
case 1:
liCase = (rand() % 5);
switch (liCase)
{
case 0:
lsStr = "Dodads";
break;
case 1:
lsStr = "Thingamajigs";
break;
case 2:
lsStr = "Whatchamacallits";
break;
case 3:
lsStr = "Round Tuits";
break;
default:
lsStr = "Widgets";
break;
}
break;
case 2:
liCase = (rand() % 4);
switch (liCase)
{
case 0:
lsStr = "Dore";
break;
case 1:
lsStr = "Harvey";
break;
case 2:
lsStr = "Pogo";
break;
default:
lsStr = "Nyra";
break;
}
break;
}
return lsStr;
return CString();
}
FUNCIN DOSORT
void CActiveXDlg::DoSort(void)
{
m_ctlFGrid.put_Col(0);
m_ctlFGrid.put_ColSel((m_ctlFGrid.get_Cols() - 1));
m_ctlFGrid.put_Sort(1);
}
X
void CActiveXDlg::OnMousedownMsfgrid(short Button, short Shift, long x, long y)
{
if (m_ctlFGrid.get_MouseRow() != 0)
{
m_iMouseCol = 0;
return;
}
m_iMouseCol = m_ctlFGrid.get_MouseCol();
X
void CActiveXDlg::OnMouseupMsfgrid(short Button, short Shift, long x, long y)
{
if (m_iMouseCol == 0)
return;
m_ctlFGrid.put_Redraw(FALSE);
m_ctlFGrid.put_ColPosition(m_iMouseCol, m_ctlFGrid.get_MouseCol());
DoSort();
m_ctlFGrid.SetRedraw(TRUE);
// TODO: Add your message handler code here
}
X
void CActiveXDlg::OnDblclickMsfgrid()
{
if (m_ctlFGrid.get_MouseRow() != 0)
{
m_iMouseCol = 0;
return;
}
m_iMouseCol = m_ctlFGrid.get_MouseCol();
if (m_iMouseCol == 0)
return;
m_ctlFGrid.SetRedraw(FALSE);
m_ctlFGrid.put_ColPosition(m_iMouseCol, 0);
DoSort();
m_ctlFGrid.SetRedraw(TRUE);
// TODO: Add your message handler code here
}
Conclusin
Sin lugar a duda, por medio de estos ejercicios he aprendido a utilizar mayor parte de las herramientas que nos
ofrece Visual Studio con respecto a la programacin orientada a objetos, que abarc desde agregar un simple mensaje o
cerrar una aplicacin con un botn, hasta interactuar con el ratn y teclado o bien poder apreciar el avance del valor de
una variable en una barra de control, e incluso agregar un control Active X que manualmente habilitamos. No obstante,
aprend que al trabajar con distintas versiones de este software, 2012 y 2013, resulta algo complicado migrar el proyecto
de una a otra (por supuesto considerando que un proyecto creado en una version nueva difcilmente podr abrirse en
una version anterior), esto debido al conjunto de caracteres que maneja (Unicode, Multi-Byte, Ninguno).
Por ltimo, cabe mencionar que en aquellos errores que se presentaron, no solo los mencionados sino algunos
ms por no entender lo que se deba hacer, encontr solucin a cada uno de ellos, en lugar de omitirlos y comenzar el
proyecto nuevamente; con lo que result en un mejor aprendizaje y experiencia.
Bibliografa
Teach Yourself Visual C++ in Days
http://informatica.uv.es/iiguia/AIG/docs/intro_visual.htm
http://es.wikipedia.org/wiki/Microsoft_Foundation_Classes
http://msdn.microsoft.com/es-es/library/e6w9eycd(v=vs.90).aspx
*http://social.msdn.microsoft.com/Forums/vstudio/en-US/c1b08c0a-a803-41c3-ac8c-84eba3be1ddb/faqcannot-convert-from-const-char-to-lpctstr?forum=vclanguage
*Este es una de las direcciones a las que se ingreso para buscar solucin a las complicaciones de migracin de proyecto entre las
versiones 2012 y 2013 de Microsoft Visual Studio