Programación Avanzada MFC
Programación Avanzada MFC
Nicolás Quiroz 2
1
Win32 API
Service Description
Nicolás Quiroz 4
2
Structure MFC
Nicolás Quiroz 5
CObject
Nicolás Quiroz 6
3
CCmdTarget and CWnd
Nicolás Quiroz 7
Hierarchy chart
Nicolás Quiroz 8
4
CCmdTarget
Nicolás Quiroz 9
CWnd
CFrame, CDialog, View, Controls
Nicolás Quiroz 10
5
CDC, Arrays,
Menus, Maps
Nicolás Quiroz 11
6
Desarrollo de una aplicación
Nicolás Quiroz 13
7 5
6
Nicolás Quiroz 14
7
Programando en Windows
Programación Orientada a Objetos (POO)
Programación conducida por eventos
• La secuencia en que se ejecutaran las sentencias no puede
ser prevista.
Escribir código separado para cada objeto (evento).
Un evento es una acción reconocida por un objeto
(ventana, control, etc).
Windows envía un mensaje al objeto para identificar
y ejecutar la función asociada con el objeto para ese
evento.
Un mensaje es una notificación que Windows envía
a una aplicación en ejecución para indicarle que algo
sucedió.
Nicolás Quiroz 15
Estructura
de un
programa
en
ambiente
Windows
Nicolás Quiroz 16
8
Programación Windows y DOS
Windows DOS
Nicolás Quiroz 17
Nicolás Quiroz 18
9
Mensajes
Nicolás Quiroz 19
Mapa de mensajes
Cada clase del sistema que puede recibir mensajes tiene su
propio mapa de mensajes.
Nicolás Quiroz 20
10
Caja de herramientas
Nicolás Quiroz 21
Variables
Categoría:
• Valor
int, long, doble, CString, char, etc.
• Control
Para tener acceso a los métodos de su clase
y clases base.
Nicolás Quiroz 22
11
Notación Húngara
Nicolás Quiroz 23
VarCtl.SetWindowText(cadena)
• Coloca texto en un control
VarCtl.GetWindowText(cadena)
• Recupera texto de un control
SetDlgItemText(ID_CONTROL, cadena)
• Coloca texto en un control
GetDlgItemText(ID_CONTROL, cadena)
• Obtienen texto de un control
Nicolás Quiroz 24
12
Conversión de texto a número
SetFocus()
• coloca el foco en un control
GetFocus()
• Obtiene un apuntador a el control que tiene el foco
Ejemplo:
CWnd *pWnd= GetFocus; //obtiene un apuntador
13
Mostrar o Ocultar un control
CWnd::ShowWindow( param )
SW_HIDE Hides this window and passes activation to another window.
SW_MINIMIZE Minimizes the window and activates the top-level window in
the system’s list.
SW_SHOW Activates the window and displays it in its current size and
position.
Nicolás Quiroz 27
CWnd::EnableWindow
Nicolás Quiroz 28
14
Realizar un programa de conversión entre
bases (2-36)
IDC_EDT_BASE_ENT
IDC_EDT_NUMERO
IDC_EDT_RESULTADO
IDC_BTN_CONVERTIR
IDC_EDT_BASE_SAL IDCANCEL
Nicolás Quiroz 29
15
Ejemplo
manejo de controles
Realizar un programa que convierta los grados Celcius a
Fahrenheit
9
ºF ºC 32
5
Utilizar variables de categoría Valor (double)
m_Centigrados
IDC_EDT_CENTIGRADOS
m_Fahrenheit
IDC_EDT_FAHRENHEIT
IDC_BTN_CONVERTIR
Nicolás Quiroz 31
Nicolás Quiroz 32
16
Tarea
Realizar un programa OO que convierta entre bases (octal,
decimal y hexadecimal) utilizando botones de opción.
Cuando se escribe un número se encuentra en la base
seleccionada, al dar clic sobre otro botón de opción se
convierte a esa base.
Nicolás Quiroz 33
CString
Cadenas variables
17
The String as an Array
Nicolás Quiroz 35
Extraction
Nicolás Quiroz 36
18
Conversions
MakeUpper Converts all the characters in this string to uppercase characters.
Nicolás Quiroz 37
ReverseFind Finds a character inside a larger string; starts from the end.
Nicolás Quiroz 38
19
Ejemplo
Timer
Realizar un programa que muestre la fecha y la
hora en un cuadro de texto
Manejo de timer
Nicolás Quiroz 39
SetDlgItemText(IDC_FECHA_HORA, FechaHoraTxt);
Coloca texto en un control
Nicolás Quiroz 40
20
Tiempo del sistema
función miembro Format
La clase CTime
Puede manejar la
tiempo y la
fecha.
Nicolás Quiroz 41
KillTimer(nTimer)
• Elimina un timer
• nTimer ID proporcionado por SetTimer
Mensaje WM_TIMER
• Mensaje enviado cada vez que se cumple el tiempo
Nicolás Quiroz 42
21
Crear una aplicación
windows
Que realice las operaciones de +, -, * y /
de números racionales
Basado en la clase CRacional creada
antes.
Interfaz de usuario
Nicolás Quiroz 44
22
Objeto Propiedad Valor
Propiedades
Dialog ID IDD_RACIONAL_DIALOG
cuadro de dialogo Caption Números racionales
Font size 18
Font name arial
Minimize Box true
Maximize Box true
Button ID IDCANCEL
salir Caption &Salir
Static Text ID IDC_STATIC
igual Caption =
Nicolás Quiroz 46
23
Declaración de la clase CRacional
(racional.h)
class CRacional
{
private:
int m_Numer, m_Denom;
public:
CRacional();
int ObtenerNumerador()const;
int ObtenerDenominador()const;
void AsignarNumerador(int n);
void AsignarDenominador(int d);
CRacional operator+(CRacional x);
CRacional operator-(CRacional x);
CRacional operator/(CRacional x);
CRacional operator*(CRacional x);
};
Nicolás Quiroz 47
Implementación CRacional
(racional.cpp)
CRacional::CRacional() //constructor
{
m_Numer= 0; m_Denom= 0;
}
int CRacional::ObtenerNumerador() const
{
return m_Numer;
}
int CRacional::ObtenerDenominador() const
{
return m_Denom;
}
void CRacional::AsignarNumerador(int n)
{
m_Numer=n;
}
void CRacional::AsignarDenominador(int d)
{
m_Denom=d;
}
Nicolás Quiroz 48
24
Implementación
(racional.cpp)
CRacional CRacional::operator*(CRacional x)
{
CRacional temp;
temp.m_Numer = m_Numer * x.m_Numer;
temp.m_Denom = m_Denom * x.m_Denom;
return temp;
}
CRacional CRacional::operator/(CRacional x)
{
CRacional temp;
temp.m_Numer = m_Numer / x.m_Numer;
temp.m_Denom = m_Denom / x.m_Denom;
return temp;
}
Nicolás Quiroz 49
Implementación
(racional.cpp)
CRacional CRacional::operator+(CRacional x)
{
CRacional temp;
temp.m_Numer = (m_Numer * x.m_Denom) + (m_Denom
* x.m_Numer);
temp.m_Denom = m_Denom * x.m_Denom;
return temp;
}
CRacional CRacional::operator-(CRacional x)
{
CRacional temp;
temp.m_Numer = (m_Numer * x.m_Denom) - (m_Denom
* x.m_Numer);
temp.m_Denom = m_Denom * x.m_Denom;
return temp;
}
Nicolás Quiroz 50
25
Declarar las variables miembros
Declarar en la clase CRacionalDlg:
Inicializarlas en el constructor:
void CRacionalDlg::OnBntMas()
{ char cad[20]; Botón mas
GetDlgItemText(IDC_NUM1, m_strTemp); //asigna el primer racional
m_ValorInt= strtol((const char *) m_strTemp, NULL, 10);
m_CR_N1.AsignarNumerador(m_ValorInt);
GetDlgItemText(IDC_DENOM1, m_strTemp);
m_ValorInt= strtol((const char *) m_strTemp, NULL, 10);
m_CR_N1.AsignarDenominador(m_ValorInt);
GetDlgItemText(IDC_DENOM2, m_strTemp);
m_ValorInt= strtol((const char *) m_strTemp, NULL, 10);
m_CR_N2.AsignarDenominador(m_ValorInt);
26
Editar icono
Nicolás Quiroz 53
Proyectos
Pantalla de LEDs
LCD
Brazo robótica
Base de datos visual
Puerto serie (chat)
Etc.
Nicolás Quiroz 54
27
Cajas de diálogo
Cajas de diálogo
Personalizadas
• Hechas a la medida, añadiendo controles a un formulario.
Predefinidas
• Funciones de la MFC (AfxMessageBox)
Estándar
• Diálogos comunes en Windows (abrir, imprimir, etc.)
Modal
• Caja que tiene que ser cerrada para poder continuar.
Nicolás Quiroz 56
28
MessageBox
int MessageBox( LPCTSTR lpszText, LPCTSTR
lpszCaption = NULL, UINT nType = MB_OK );
Parameters
lpszText
Points to a CString object or null-terminated string containing the
message to be displayed.
lpszCaption
Points to a CString object or null-terminated string to be used
for the message-box caption.
If lpszCaption is NULL, the default caption “Error” is used.
nType
Specifies the contents and behavior of the message box.
Nicolás Quiroz 57
MessageBox
The following shows the various system icons that
can be used in a message box:
MB_ICONQUESTION
MB_ICONEXCLAMATION and
MB_ICONWARNING
MB_ICONASTERISK and
MB_ICONINFORMATION
Nicolás Quiroz 58
29
Return Values
The return value is zero if there is not enough memory to create
the message box.
If the function succeeds, the return value is one of the following
menu-item values returned by the dialog box:
Value Meaning
IDABORT Abort button was selected.
IDCANCEL Cancel button was selected.
IDIGNORE Ignore button was selected.
IDNO No button was selected.IDOKOK button was selected.
IDRETRY Retry button was selected.
IDYES Yes button was selected.
Nicolás Quiroz 59
Nicolás Quiroz 60
30
Cajas de diálogo comunes
CFileDialog Abrir o guardar un archivo
CColorDialog Seleccionar un color
CFontDialog Seleccionar un tipo de letra
CPrintDialog Imprimir un documento
…
Nicolás Quiroz 61
Nicolás Quiroz 62
31
CFileDialog
Construction
CFileDialog Constructs a CFileDialog object.
Operations
DoModal Displays the dialog box and allows the user to make a
selection.
GetPathName Returns the full path of the selected file.
GetFileName Returns the filename of the selected file.
GetFileExt Returns the file extension of the selected file.
GetFileTitle Returns the title of the selected file.
GetNextPathName Returns the full path of the next selected file.
GetReadOnlyPref Returns the read-only status of the selected file.
GetStartPosition Returns the position of the first element of the
filename list.
Nicolás Quiroz 63
Archivos
Clase CFile
32
Archivos
Un archivo es una colección de información que
almacenamos en un soporte magnético u óptico,
para poder manipular en cualquier momento.
texto Leer
archivos
binarios Escribir
Disco
En cada sector
sólo existe un
archivo.
Nicolás Quiroz 66
33
Acceso
Acceso secuencial
• posiciones consecutivas
Acceso Aleatorio o directo
• Se accede directamente a la posición deseada
0 1 2 3 4 5 6 7 8 9
h o l a m u n d o
Apuntador
Nicolás Quiroz 67
Input/Output:
Read Reads (unbuffered) data from a file at the current file position.
34
CFile Class Members
Position:
Seek Positions the current file pointer.
SeekToBegin Positions the current file pointer at the beginning of the file.
SeekToEnd Positions the current file pointer at the end of the file.
Nicolás Quiroz 69
Status
GetPosition Retrieves the current file pointer.
Nicolás Quiroz 70
35
CFile Class Members
Static
GetStatus Retrieves the status of the specified file (static, virtual function).
SetStatus Sets the status of the specified file (static, virtual function).
Nicolás Quiroz 71
CFile::CFile
Nicolás Quiroz 72
36
CFile::CFile
CFile::shareDenyWrite Opens the file and denies other processes write
access to the file. Create fails if the file has been opened in compatibility
mode or for write access by any other process.
Parameters:
lpszFileName
A string that is the path to the desired file. The path can be relative,
absolute, or a network name (UNC).
nOpenFlags
A UINT that defines the file’s sharing and access mode. It specifies the
action to take when opening the file. You can combine options by using
the bitwise-OR ( | ) operator. One access permission and one share
option are required.
pError
A pointer to an existing file-exception object that will receive the status
of a failed operation.
Nicolás Quiroz 74
37
virtual UINT Read( void* lpBuf, UINT nCount );
Return Value
The number of bytes transferred to the buffer. Note that for all CFile
classes, the return value may be less than nCount if the end of file was
reached.
Parameters
lpBuf
Pointer to the user-supplied buffer that is to receive the data read from
the file.
nCount
The maximum number of bytes to be read from the file. For text-mode
files, carriage return–linefeed pairs are counted as single characters.
Nicolás Quiroz 75
Parameters
lpBuf
A pointer to the user-supplied buffer that contains the data to
be written to the file.
nCount
The number of bytes to be transferred from the buffer. For
text-mode files, carriage return–linefeed pairs are counted as
single characters.
Nicolás Quiroz 76
38
virtual LONG Seek( LONG lOff, UINT nFrom );
Return Value
If the requested position is legal, Seek returns the new
byte offset from the beginning of the file. Otherwise, the
return value is undefined and a CFileException object is
thrown.
Parameters
lOff
Number of bytes to move the pointer.
nFrom
Pointer movement mode. Must be one of the following
values:
Nicolás Quiroz 77
Return Value
The length of the file.
Remarks
Obtains the current logical length of the file in bytes, not
the amount.
Nicolás Quiroz 78
39
virtual LONG Seek( LONG lOff, UINT nFrom );
CFile::end Move the file pointer lOff bytes from the end
of the file. Note that lOff must be negative to seek into the
existing file; positive values will seek past the end of the
file.
Nicolás Quiroz 79
Puerto Paralelo
PC
Programa visual
40
Puerto Paralelo
Existen actualmente varias versiones de las
especificaciones del puerto original
Bi-direccional (PS/2)
Enhanced Parallel Port (EPP)
Extended Capability Port (ECP)
Nicolás Quiroz 81
0x379 (Entrada)
Bit ~7 6 5 4 3 2 1 0
Pin 11 10 12 13 15 - - -
0x37A (salida)
Bit 7 6 5 4 ~3 2 ~1 ~0
Pin - - I/O IRQ 17 16 14 1
Nicolás Quiroz 82
41
Conector DB-25
Nicolás Quiroz 83
Desplegador de
7 Segmentos dec hex bin
pgfedcba
Encender un desplegador de 7
segmentos que muestre los 0 3F 00111111
dígitos del 0 al 9. 1 06 00000110
Utilice código de 7 segmentos.
2 5B 01011011
3 4F 01001111
a
4 66 01100110
f g b 5 6D 01101101
6 7D 01111101
e c
7 47 01000111
d p 8 7F 01111111
9 67 01100111
Nicolás Quiroz 84
42
Manejo de mensajes
MSG msg;
Nicolás Quiroz 85
Archivo.Write(BufferTransferencia,numBytes);
}
catch(CFileException *e)
{
//codigo para manejo excepción
e->ReportError();
e->Delete();
}
Nicolás Quiroz 86
43