0% found this document useful (0 votes)
104 views

Programación Avanzada MFC

The document discusses Microsoft Foundation Classes (MFC) and the Win32 API. MFC was developed to simplify creating Windows applications by providing C++ classes that wrap key Win32 API features. It supports Windows objects like windows, dialog boxes, and controls as well as graphics objects. The core classes include CObject, CCmdTarget, and CWnd. Programming in Windows uses event-driven programming and messages to communicate between objects.

Uploaded by

cesar aguirre
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views

Programación Avanzada MFC

The document discusses Microsoft Foundation Classes (MFC) and the Win32 API. MFC was developed to simplify creating Windows applications by providing C++ classes that wrap key Win32 API features. It supports Windows objects like windows, dialog boxes, and controls as well as graphics objects. The core classes include CObject, CCmdTarget, and CWnd. Programming in Windows uses event-driven programming and messages to communicate between objects.

Uploaded by

cesar aguirre
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Programming Visual

MC Nicolás Quiroz Hernández

MFC and the Win32 API

The term Win32 is used to describe an Application


Programming Interface (API).

Common to all of the Microsoft 32-bit Windows


platforms (Windows 95, Windows 98, Windows
NT, Microsoft Windows CE, and Window Vista)

The Win32 API is a set of functions, structures,


messages, macros, and interfaces that provides a
consistent interface to enable you to develop
applications for any of the Win32 platforms.

Nicolás Quiroz 2

1
Win32 API
Service Description

Window Provides the means to create and manage a user


Management interface.
Window Provides a set of common user interface controls.
Controls Using the common controls helps keep an
application's user interface consistent with that of
the shell and other applications. It also saves a
significant amount of development time.
Shell Features Provides access to system objects and resources
such as files, storage devices, printers, and
network resources.
Graphics Provides functions and related structures used to
Device generate graphical output for displays, printers,
Interface and other graphical devices.
System Provides access to the resources of the computer
Services via features of the underlying operating system.
Nicolás Quiroz 3

Microsoft Foundation Class (MFC)


La Biblioteca de clases de Microsoft

MFC was developed to simplify and speed up the


development of Windows applications by
providing a set of C++ classes that encapsulate
key features of the Win32 API.

Da soporte a los objetos Windows: ventanas,


cajas de dialogo, controles (cajas de texto,
botones, etc.); objetos GID: pens (plumas),
brushes (pinceles), fonts (fuentes) y bitmaps
(mapa de bits). Manejo de mensajes.

Básicamente dos objetos: Ventanas y controles.

Nicolás Quiroz 4

2
Structure MFC

Nicolás Quiroz 5

CObject

CObject is the base class for a large number of the MFC


classes.

CObject provides basic services, including serialization


(loading and saving data objects to a file); run-time class
information; diagnostic and debugging support (validations
and dumps); and compatibility with collection classes.

Nicolás Quiroz 6

3
CCmdTarget and CWnd

The CCmdTarget class is the base class for all


objects that are capable of handling Windows
messages.

The CWnd class represents a window. The fact that


the CDialog class is derived from the CWnd
class illustrates the idea that a dialog box is a
specialized type of window.

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

Classes not derived from CObject


Nicolás Quiroz 12

6
Desarrollo de una aplicación

*.dsw cargar el proyecto


*.dsp ordenes para crear el
ejecutable
*.rc Recursos que la aplicación
utiliza (iconos, mapas de bits, y
cursores)
*.clw información de las clases,
manejada por asistente de clases
*.cpp archivos fuentes
implementación de la clases
*.h declaración de una clase

Nicolás Quiroz 13

Partes de una ventana


1 3
2

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

Windows funciona como una máquina virtual.

Nicolás Quiroz 17

Ejecución de una aplicación Windows

1. Se construye un objeto global que representa la


aplicación.
2. Windows llama a la función WinMain de la MFC. Esta
función es punto de entrada y salida.
3. WinMain llama a la función InitInstance del objeto
aplicación.
4. El objeto aplicación crea el objeto ventana principal.
5. El objeto aplicación visualiza el objeto ventana principal.
6. WinMain llama a la función miembro Run del objeto
aplicación.
7. El objeto aplicación ejecuta el bucle de mensajes.
8. El objeto ventana principal procesa cualquier mensaje
que se produzca.

Nicolás Quiroz 18

9
Mensajes

Mensajes de órdenes (WM_COMMAND). Se genera cuando


el usuario selecciona una orden del menú, un acelerador o
un botón de la barra de menús.

Mensajes de notificación. Enviado por Windows a una


ventana en respuesta a una tecla pulsada
(WM_COMMAND), al pulsar un botón (BN_CLICKED), etc.

Mensajes de ventana (WM_xxx exepto WM_COMMAND).


Mensajes no relacionados con controles. Mensajes
generados por el sistema o por el usuario.

Nicolás Quiroz 19

Mapa de mensajes
Cada clase del sistema que puede recibir mensajes tiene su
propio mapa de mensajes.

El mapa de mensajes asocia los mensajes con los


manipuladores que los manejan (funciones).

// Generated message map functions


//{{AFX_MSG(CPrimerDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()

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

Colocar y Obtener texto en un control

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

Retrieves the text of the control identified by nID.

UINT GetDlgItemInt( int nID,


BOOL* lpTrans = NULL,
BOOL bSigned = TRUE ) const;

Sets the text of a given control in a dialog box to the string


representation of a specified integer value.
void SetDlgItemInt( int nID,
UINT nValue,
BOOL bSigned = TRUE );
Nicolás Quiroz 25

Obtener un apuntador a un control


o ID, Foco
GetDlgItem(IDC_NOMBRE)
• Regresa un apuntador al control
CWnd::GetDlgCtrlID()
• devuelve el ID de un control

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

m_ID=pWnd-> GetDlgCtrlID(); //obtiene el ID del


//control enfocado
Nicolás Quiroz 26

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_RESTORE Activates and displays the window. If the window is


minimized or maximized, Windows restores it to its original size and position.

SW_SHOW Activates the window and displays it in its current size and
position.

SW_SHOWMAXIMIZED Activates the window and displays it as a


maximized window.

SW_SHOWMINIMIZED Activates the window and displays it as an icon.

Nicolás Quiroz 27

Habilitar una control

CWnd::EnableWindow

BOOL EnableWindow( BOOL bEnable = TRUE );


si bEnable es:
FALSE Deshabilitar
TRUE Habilitar

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

Método para el botón convertir


OnBtnConvertir()
char Num[15],Resul[15],BaseEnt[5],BaseSal[5];
long entBaseEnt,entBaseSal,Numero;

GetDlgItemText(IDC_EDT_NUMERO, Num,15); Obtener los textos


GetDlgItemText(IDC_EDT_BASE_ENT, BaseEnt,5); de los cuadros

GetDlgItemText(IDC_EDT_BASE_SAL, BaseSal,5); EditBox

entBaseEnt = strtol(BaseEnt, NULL,10);


Convertir texto a
entBaseSal = strtol(BaseSal, NULL,10); número
Numero= strtol(Num,NULL, entBaseEnt);
Convertir número
ltoa(Numero, Resul, entBaseSal); a texto

SetDlgItemText(IDC_EDT_RESULTADO, Resul); Mostrar resultados


en texto
Nicolás Quiroz 30

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

Actualizar y recuperar variables


de tipo valor
UpdateData(Argumento)

Permite iniciar los controles de una ventana o


recuperar y validar los datos de los controles de
una ventana.
Argumento es:
TRUE Recupera
FALSE Actualiza las variables miembro

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

GetLength Returns the number of characters in a CString object. For


multibyte characters, counts each 8-bit character; that is, a
lead and trail byte in one multibyte character are counted
as two characters.
IsEmpty Tests whether a CString object contains no characters.
Empty Forces a string to have 0 length.
GetAt Returns the character at a given position.
operator [ ] Returns the character at a given position — operator
substitution for GetAt.
SetAt Sets a character at a given position.
operator LPCTSTR Directly accesses characters stored in a CString object as
a C-style string.

Nicolás Quiroz 35

Extraction

Mid Extracts the middle part of a string.

Left Extracts the left part of a string.

Right Extracts the right part of a string.

SpanIncluding Extracts a substring that contains only the characters in a set.

SpanExcluding Extracts a substring that contains only the characters not in a


set.

Nicolás Quiroz 36

18
Conversions
MakeUpper Converts all the characters in this string to uppercase characters.

MakeLower Converts all the characters in this string to lowercase characters.


MakeReverse Reverses the characters in this string.
Replace Replaces indicated characters with other characters.
Remove Removes indicated characters from a string.
Insert Inserts a single character or a substring at the given index within
the string.
Delete Deletes a character or characters from a string.
Format Format the string as sprintf does.
FormatV Formats the string as vsprintf does.
TrimLeft Trim leading whitespace characters from the string.
TrimRight Trim trailing whitespace characters from the string.
FormatMessage Formats a message string.

Nicolás Quiroz 37

Searching and Comparison


Find Finds a character or substring inside a larger string.

ReverseFind Finds a character inside a larger string; starts from the end.

FindOneOf Finds the first matching character from a set.

operator == <, etc. Comparison operators (case sensitive).

Compare Compares two strings (case sensitive).


CompareNoCase Compares two strings (case insensitive).
Collate Compares two strings (case sensitive, uses locale-specific
information).
CollateNoCase Compares two strings (case insensitive, uses locale-
specific information).

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

Desplegar la fecha y la hora


del sistema
CTime FechaHora=CTime::GetCurrentTime();
Obtiene la fecha y el tiempo actual del sistema

CString FechaHoraTxt=FechaHora.Format(“%A %d -%b- %Y”);


Conversión a texto con formato

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

Activar o desactivar un Timer


SetTimer(nTimer, miliseg, NULL)
• Activar un timer
• nTimer es un entero que identifica el timer
• Miliseg es un entero que indica el tiempo en ms

KillTimer(nTimer)
• Elimina un timer
• nTimer ID proporcionado por SetTimer

Mensaje WM_TIMER
• Mensaje enviado cada vez que se cumple el tiempo

Manejar el mensaje WM_TIMER para el cuadro de dialogo.


Crear el timer en la función OnInitDialog

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

Edit Box ID IDC_NUM1


Numerador 1
Edit Box ID IDC_DENOM1
Denominador 1
Edit Box ID IDC_NUM2
Numerador 2
Edit Box ID IDC_DENOM2
Denominador 2
Edit Box ID IDC_RES_NUM
Resultado Numerador
Edit Box ID IDC_RES_DENOM
Resultado Denominador
Button ID IDC_BNT_MAS
sumar Caption +
Button ID IDC_BNT_MENOS
restar Caption -
Button ID IDC_BNT_POR
producto Caption *
Button ID IDC_BNT_DIV
división Caption /
Nicolás Quiroz 45

Propiedades

Objeto Propiedad Valor

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 =

Static Text ID IDC_STATIC


Caption operación

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:

CString m_strTemp; //almacenar una cadena


int m_ValorInt; //almacenar la cadena como numero
CRacional m_CR_N1;
CRacional m_CR_N2;
CRacional m_CR_N3;

Inicializarlas en el constructor:

CRacionalDlg::CRacionalDlg(CWnd* pParent /*=NULL*/)


{
//{{AFX_DATA_INIT(CRacionalDlg)
m_strTemp = _T("");
m_ValorInt = 0;
//}}AFX_DATA_INIT

}
Nicolás Quiroz 51

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_NUM2, m_strTemp); //asigna el segundo racional


m_ValorInt= strtol((const char *) m_strTemp, NULL, 10);
m_CR_N2.AsignarNumerador(m_ValorInt);

GetDlgItemText(IDC_DENOM2, m_strTemp);
m_ValorInt= strtol((const char *) m_strTemp, NULL, 10);
m_CR_N2.AsignarDenominador(m_ValorInt);

m_CR_N3=m_CR_N1 + m_CR_N2; //suma los dos racionales


ltoa(m_CR_N3.ObtenerNumerador(), cad, 10);
SetDlgItemText(IDC_RES_NUM, cad);
ltoa(m_CR_N3.ObtenerDenominador(), cad, 10);
SetDlgItemText(IDC_RES_DENOM, cad);
}
Nicolás Quiroz 52

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.

Use the global function AfxMessageBox instead of this member


function to implement a message box in your application.

Nicolás Quiroz 57

MessageBox
The following shows the various system icons that
can be used in a message box:

MB_ICONHAND, MB_ICONSTOP, and


MB_ICONERROR

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

Specify one of the following flags to indicate the


buttons contained in the message box:
Flag Meaning
MB_ABORTRETRYIGNORE The message box contains three push
buttons: Abort, Retry, and Ignore.
MB_OK The message box contains one push
button: OK. This is the default.
MB_OKCANCEL The message box contains two push buttons:
OK and Cancel.
MB_RETRYCANCEL The message box contains two push
buttons: Retry and Cancel.
MB_YESNO The message box contains two push buttons:
Yes and No.
MB_YESNOCANCEL The message box contains three push
buttons: Yes, No, and Cancel.

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

Cajas de diálogo comunes

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

Operaciones con archivos:


Abrir el archivo
Operaciones de lectura/escritura
Cerrar el archivo
Nicolás Quiroz 65

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

CFile Class Members


Construction:
CFile Constructs a CFile object from a path or file handle.

Abort Closes a file ignoring all warnings and errors.

Duplicate Constructs a duplicate object based on this file.

Open Safely opens a file with an error-testing option.

Close Closes a file and deletes the object.

Input/Output:
Read Reads (unbuffered) data from a file at the current file position.

Write Writes (unbuffered) data in a file to the current file position.

Flush Flushes any data yet to be written.


Nicolás Quiroz 68

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.

GetLength Retrieves the length of the file.

SetLength Changes the length of the file.

Nicolás Quiroz 69

CFile Class Members

Status
GetPosition Retrieves the current file pointer.

GetStatus Retrieves the status of this open file.

GetFileName Retrieves the filename of the selected file.

GetFileTitle Retrieves the title of the selected file.

GetFilePath Retrieves the full file path of the selected file.

SetFilePath Sets the full file path of the selected file.

Nicolás Quiroz 70

35
CFile Class Members

Static

Rename Renames the specified file (static function).

Remove Deletes the specified file (static function).

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

CFile::modeCreate Directs the constructor to create a new file. If the


file exists already, it is truncated to 0 length.

CFile::modeNoTruncate Combine this value with modeCreate. If the


file being created already exists, it is not truncated to 0 length. Thus
the file is guaranteed to open, either as a newly created file or as an
existing file. This might be useful, for example, when opening a
settings file that may or may not exist already. This option applies to
CStdioFile as well.

CFile::modeRead Opens the file for reading only.

CFile::modeReadWrite Opens the file for reading and writing.

CFile::modeWrite Opens the file for writing only.

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.

CFile::shareExclusive Opens the file with exclusive mode, denying other


processes both read and write access to the file. Construction fails if the
file has been opened in any other mode for read or write access, even by
the current process.

CFile::shareCompat This flag is not available in 32 bit MFC. This flag


maps to CFile::shareExclusive when used in CFile::Open.

CFile::typeText Sets text mode with special processing for carriage


return–linefeed pairs (used in derived classes only).

CFile::typeBinary Sets binary mode (used in derived classes only).


Nicolás Quiroz 73

virtual BOOL Open( LPCTSTR lpszFileName, UINT


nOpenFlags, CFileException* pError = NULL );

Return Value: Nonzero if the open was successful; otherwise 0. The


pError parameter is meaningful only if 0 is returned.

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

virtual void Write( const void* lpBuf, UINT nCount );

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

virtual DWORD GetLength( ) const;

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::begin Move the file pointer lOff bytes forward from


the beginning of the file.

CFile::current Move the file pointer lOff bytes from the


current position in the file.

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

Dirección del puerto


0x378 (salida)
Bit 7 6 5 4 3 2 1 0
Pin 9 8 7 6 5 4 3 2

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

Conector tipo D hembra

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;

if ( ::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))


{
TranslateMessage( &msg );
DispatchMessage( &msg );
}

Nicolás Quiroz 85

Manejo de una excepción

try { //prueba posible excepción

Archivo.Write(BufferTransferencia,numBytes);
}
catch(CFileException *e)
{
//codigo para manejo excepción
e->ReportError();
e->Delete();
}

Nicolás Quiroz 86

43

You might also like