Introduction
Previously we learned how to use a good application that makes sense as a first program, now I'm trying to practice the slider control with the same as what I used in the first example which are the buttons and the Edit controls.
Using the Code
The idea is too simple. Take the ASCII code of the input string, break it into characters and then shift every ASCII code with a certain code obtained from the Key (slider control).
How to do it? It's simple even for me; as a beginner I thought it would be a very big challenge. We are going to create a new MFC project, then add to it two buttons; one edit control and one slider control. Then we add a member variable for the slider control and let’s call it m_ctrlSlide
with the type CSliderCtrl
. Another member variable we should add to the Edit Control with the type CString
and let’s call it m_ctrlEdit
. I did limit the max number of character in this string to 80 and you can modify it as you like.
m_CtrlSlider.SetRange(0,13);
m_CtrlSlider.SetTicFreq(13);
After that, the simple programming practice will start when we will assign each button for a function to reverse the other one, which are Encrypt and Decrypt.
The below source code is what I did in every one of those handlers respectively.
void CCaesarsEncrypterDlg::OnBnClickedEncrypt()
{
CString strTmp;
int m_nKey,m_nlength;
m_nKey=m_CtrlSlider.GetPos();
UpdateData(TRUE);
m_nlength=m_strText.GetLength();
for(int i=0;i<m_nlength;i++)
{
char cTemp = m_strText[i];
cTemp += m_nKey;
strTmp += cTemp;
}
m_strText = strTmp;
UpdateData(FALSE);
}
void CCaesarsEncrypterDlg::OnBnClickedDecrypt()
{
CString strTmp;
int m_nKey,m_nlength;
m_nKey=m_CtrlSlider.GetPos();
UpdateData(TRUE);
m_nlength=m_strText.GetLength();
for(int i=0;i<m_nlength;i++)
{
char cTemp = m_strText[i];
cTemp -= m_nKey;
strTmp += cTemp;
}
m_strText = strTmp;
UpdateData(FALSE);
}
One final note: This program is not done for encryption purposes but for learning how to read the sliders' controls and process it. Although this application doesn't rotate the last ASCII character to the first one like it should, you can play with it in the messenger :-).
Have a nice day!
History
- 5th March, 2008: Initial post