반응형
출처 : http://www.codeguru.com/Cpp/controls/staticctrl/article.php/c2907

extended Use of CStatic Class
Rating: none

Norm Alomond (view profile)
August 6, 1998

CLabel image

 Downloa
(continued)

 Download Source Code and Example


Every wanted a static control that behaved like a Visual Basic(yuk!) label control? Well this could be just the thing you might be looking for. The first cut version of this MFC extension class will allow you to change the text, font attributes (weight, underline, size, name), text color, background color and border style.

I've called the simple class CLabel and is simple to use in dialog boxes, just follow this simple instructions.

  1. Design the dialog box in the normal why.
  2. Create a OnInitDialog function using the class wizard.
  3. Add Label.cpp and Label.h to your project.
  4. #Include <label.h> in your dialog .cpp file.
  5. Any static controls that need enhancing, give each control a unique ID.
  6. Assign a member control (CLabel) to each ID using the class wizard.
  7. In OnInitDialog change a static controls appearing the functions provided. (See Label.h)

API of CLabel

CLabel& SetBkColor(COLORREF crBkgnd) Set the background colour of the control
CLabel& SetText(const CString& strText) Sets the text of the controls
CLabel& SetTextColor(COLORREF crText) Sets the text colour of the control
CLabel& SetFontBold(BOOL bBold) Toggles the state of the bold attribute of the text in the control
CLabel& SetFontName(const CString& strFont) The the fonts face name in the control
CLabel& SetFontUnderline(BOOL bSet) Toggles the state of the underline font attribute of the control
CLabel& SetFontItalic(BOOL bSet) Toggles the state of the italic font attribute of the control
CLabel& SetFontSize(int nSize) Sets the fonts size in points.
CLabel& SetSunken(BOOL bSet) Toggles the state of the sunken attribue of the control
CLabel& SetBorder(BOOL bSet) Toggles the state of the borders attribute
CLabel& FlashText(BOOL bSet) Toggles the state of the text flashing attribute
CLabel& FlashBackground(BOOL bSet) Toggles the state of the text flashing attribute
CLabel& SetLink(BOOL bLink) Toggles the state of the link attribute (allows label to become internet link)
CLabel& SetLinkCursor(HCURSOR hCursor) Sets the cursor for the link.

Example of CLabel

    m_fname.SetFontName("System");
    m_fsize.SetFontSize(14);
    m_uline.SetFontUnderline(TRUE);
    m_tcolor.SetTextColor(RGB(255,0,0));
    m_bcolor.SetBkColor(RGB(0,255,255));
    m_italics.SetFontItalic(TRUE);
    m_bold.SetFontBold(TRUE);
    m_border.SetBorder(TRUE);
    m_sunken.SetSunken(TRUE);

    m_monty.SetFontName("Arial");
    m_monty.SetFontSize(12);
    m_monty.SetTextColor(RGB(255,255,0));
    m_monty.SetFontUnderline(TRUE);
    m_monty.SetBkColor(RGB(0,0,0));
    m_monty.SetFontItalic(TRUE);
    m_monty.SetFontBold(TRUE);
    m_monty.SetBorder(TRUE);
    m_monty.SetSunken(TRUE);

Last Updated: May 30 1998


 Free Trial: SQL Toolbelt--Get 12 powerful & intuitive tools to burn through SQL Server chores fast!  
 Could You Use an Extra $30,000 Right Now? Are You a Mobile or Web App Developer? Click here to learn more!  
 The next generation of Windows—join the conversation.  
 Build Full Web Applications in 5 Minutes. Learn more.  
 30-day Trial: Hitachi IT Operations Analyzer software monitors multivendor server, network & storage assets.  

반응형

'Tech > 프로그래밍' 카테고리의 다른 글

XML Reader만들기  (0) 2009.07.26
[C++] 안전문자열 함수 관련 자료  (0) 2009.07.14
CStdioFile: GetPosition, Seek 질문답변  (0) 2009.05.22
COM/ATL 관련 tip  (0) 2009.04.27
COM Versioning관련해서 알아볼 것  (0) 2009.02.18
반응형
출처 : http://www.codeguru.com/forum/printthread.php?t=456659

nados29 July 6th, 2008 11:28 AM

CStdioFile: GetPosition, Seek
 
Dear all,
I am using CStdioFile to read a certain file.... however, there is a strange behaviour that I am facing... in the middle of reading the file (called MyFile) i do the following:

DWORD dw = MyFile.GetPosition();
MyFile.Seek(dw, 0);

I guess this should not make any difference in the current file position. Surprisingly, I noticed that the current file position changes.

I saw MyFile in the QuickWatch just before these 2 lines (to see the content from the current position), then did the same after these 2 lines of code, and found that the position is changing.

Please advise,
Thank you.

Paul McKenzie July 6th, 2008 11:39 AM

Re: CStdioFile: GetPosition, Seek
 
Quote:

Originally Posted by nados29
Dear all,
I am using CStdioFile to read a certain file.... however, there is a strange behaviour that I am facing... in the middle of reading the file (called MyFile) i do the following:

DWORD dw = MyFile.GetPosition();
MyFile.Seek(dw, 0);

How did you open the file? Did you open it as a text file or a binary file?

If you opened it as a text file, do not use these routines on files open in text mode. These functions such as GetPosition() and Seek() are only reliable on files open in binary mode. There is carriage-return/line feed translation that occurs when you use CStdioFile to open a file in text mode or if you use any file I/O function that opens a file in text mode. 

If you attempt to use Seek(), GetPosition(), fseek(), ftell(), etc. on text mode files, you'll just be fighting all day with the hidden CR/LF translation going on, and your program may never work correctly. If you really want to control where things are written or read in a file, right down to the exact byte within the file, the file must be opened in binary mode, meaning you must use the textBinary flag when opening the file.

I have never used CStdioFile, so I'm going by what the MSDN documentation states on the flags, and textBinary claims to open the file in binary mode.

Regards,

Paul McKenzie

nados29 July 6th, 2008 11:45 AM

Re: CStdioFile: GetPosition, Seek
 
Thank u for the information,
Actually I am opening the file in text mode; but I am using the Seek and GetPosition because I want to jump to a specific segment of the file, so ReadString is not sufficient to do that.

Any hints to do that in a text file?
Thank you

Paul McKenzie July 6th, 2008 11:53 AM

Re: CStdioFile: GetPosition, Seek
 
Quote:

Originally Posted by nados29
Thank u for the information,
Actually I am opening the file in text mode; but I am using the Seek and GetPosition because I want to jump to a specific segment of the file,

You can't open a file in text mode and reliably jump to a location of your choosing, since that file offset you're using isn't the true file offset. 

Jumping to specific locations in files is why binary mode is used. Since there is CR/LF translation going on behind the scenes in text mode, using Seek() is not going to work reliably. Binary mode is the way to open files and manipulate where things are being read or written to on the byte level.
Quote:

Any hints to do that in a text file?
Read the entire file into a buffer, change the buffer, write the buffer to a new file, rename new file to old file.

Regards,

Paul McKenzie

Newlena July 27th, 2008 10:29 AM

Re: CStdioFile: GetPosition, Seek
 
Paul McKenzie, Can you paste an example for your idea? Thank a lot.

i have a file:
item1 232
item2 5455
item3 12
....
itemn 2345

not i want to replace line "item2 5455" with "item 44", i just get "item 4455".
but if i want to replace line "item2 5455" with "item 444444", i get
"item2 444444tem3 12"

darwen July 27th, 2008 11:17 AM

Re: CStdioFile: GetPosition, Seek
 
You can't 'delete' characters from a file. Only overwrite what is already there.

You should do what PMK says : read the whole file into a buffer, change the buffer and then resave the file using the altered buffer.

What happens if you have an edit control with 'aa bb cc' in it, turn insert off (hit the insert key), position the cursor on the first 'b' and type 'hello' - what do you get ? You don't get 'aa hellobb cc' you get 'aa hello'. Files work the same way : any characters saved to the file only overwrite what's there (including newlines which is why you're getting the results you are).

Darwen.

darwen July 27th, 2008 01:03 PM

Re: CStdioFile: GetPosition, Seek
 
I was feeling generous : here's code which will load in the file, change an item and then save the file out again.

Code:

#include "stdafx.h"

#include <afxwin.h>
#include <vector>
#include <algorithm>

struct FileValues
{
    CString m_sName;
    CString m_sValue;
} ;

const wchar_t FileName[] = L"TextFile.txt";

void ReadFileValues(std::vector<FileValues> &values)
{
    CStdioFile file(FileName, CFile::modeRead);
    
    CString line;
    
    while (file.ReadString(line))
    {
        if (line.GetLength() > 0)
        {
            int indexOfSpace = line.Find(L' ');
            
            if (indexOfSpace > 0)
            {
                std::vector<FileValues>::iterator item = values.insert(values.end(), FileValues());
                item->m_sName = line.Left(indexOfSpace);
                item->m_sValue = line.Right(line.GetLength() - (1 + indexOfSpace));
            }
        }
    }
}

class PredicateNameEquals    
{
public:
    PredicateNameEquals(const CString &name)
        : m_sName(name)
    {
    }
    
    bool operator() ( const FileValues &value ) const
    {
        return value.m_sName == m_sName;
    }
    
private:
    const CString &m_sName;    
} ;

void ReplaceValueWith(std::vector<FileValues> &values, const CString &itemName, const CString &newItemName, const CString &newItemValue)
{
    std::vector<FileValues>::iterator item = std::find_if(values.begin(), values.end(), PredicateNameEquals(itemName));
    
    if (item != values.end())
    {
        item->m_sName = newItemName;
        item->m_sValue = newItemValue;
    }
}

class FunctorWriteToFile
{
public:
    FunctorWriteToFile(CStdioFile &file)
        : m_file(file)
    {
    }
    
    void operator() (const FileValues &values) const
    {
        m_file.WriteString(values.m_sName);
        m_file.WriteString(L" ");
        m_file.WriteString(values.m_sValue);
        m_file.WriteString(L"\n");
    }
    
private:
    CStdioFile &m_file;
};

void SaveFileValues(const std::vector<FileValues> &values)
{
    CStdioFile file(FileName, CFile::modeWrite);
    
    std::for_each(
        values.begin(),
        values.end(),
        FunctorWriteToFile( file ) );    
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<FileValues> values;
    ReadFileValues(values);
    
    ReplaceValueWith(values, "item2", "item", "44");
    SaveFileValues(values);
    
    return 0;
}

I know it's mixing MFC and STL which isn't advisable, but you are using CStdioFile so I didn't want to give you an example using ifstream/ofstream which is the method I would normally use.

Darwen.
반응형
반응형

[펌] 미니 ATL 프로그래밍
간단예제 만들기
출처 : http://blog.daum.net/aswip/7588370

[Q&A] CoInitialize, CoUninitialize, Release 관련 Scope질문답변
 XML 데이타처리와 관련하여  | VC++ 일반 2006-07-17 오후 9:05:47
장현철 (hcchang)  장현철님께 메시지 보내기장현철님을 내 주소록에 추가합니다.장현철님의 개인게시판 가기 번호: 590188   / 평점:  (-)  / 읽음:27

 // 기동 및 처리과정

 

    ::CoInitialize(NULL);

    CreateDOMXML();

 

    CString     strPath;

 

    // 모듈의 패스를 취득한다..

    CGLPFileDirUtility  MessageFileDir;

    strPath = MessageFileDir.GetExeModuleDirectory();

    strPath += GLP_MESSAGEFILENAME;

    LoadXMLFile(strPath);

 

// 종료시

 

    ::CoUninitialize();

 

* 위에서 기동및 처리과정에서는 전혀 문제가 없습니다. 그리고 제가 원하는 XML 데이타도

잘 가져 오는데요

 

종료시 과정인 ::CoUninitialize() 함수만 실행했다하면

 

VC98/include/COMIP.H의 아래부분에서

 

    // The Interface.

    //

    Interface* m_pInterface;

 

    // Releases only if the interface is not null.

    // The interface is not set to NULL.

    //

    void _Release() throw()

    {

        if (m_pInterface != NULL) {

            m_pInterface->Release();         <---------------- 여기요

        }

    }

 

에서 에러라구 팍 올라옵니다.  좀 누가 아시면 좀 알려주세요

죽겠습니다.

 [답변]... 2006-07-17 오후 11:00:01
이기탁 (snaiper)  이기탁님께 메시지 보내기이기탁님을 내 주소록에 추가합니다.이기탁님의 개인게시판 가기 번호: 590201   / 평점:  (-)  

XML 이면 IXML???Ptr 류의 스마트 포인터를 쓰셨을 것 같군요.

맞죠? 그걸 혹시 멤버 변수로 하셨습니까?

 

그런 경우에 문제가 될 수 있는데 CoUninitialize 를 하고 나면 이 이후에

COM API 호출하느건 다 에러 떨어집니다. 그런데 아마 이걸 멤버 함수

리턴하기 전에 하셨을 것 같은데 맞죠?

 

그럼 나중에 클래스 인스턴스가 파괴되면서 내부적으로 Release 를 다 부르는데

이미 CoUninitialize 가 호출된 후이기 때문에 그렇게 되는겁니다.

 

뭐 꼭 이런 상황이 아니더라도 비슷하게 CoInitilize 와 CoUnintialize 사이의 스코프보다

스마트 포인터 객체의 스코프가 더 크면 저런 문제가 생깁니다.

변수 스코프를 다시 확인해보세요

반응형
반응형
SXS Activation Context --- Activate and Deactivate

Isolated Applications and Side-by-side Assemblies
반응형
반응형
Thread관련프로그램에서 ntdll.dll에서 죽는 경우가 생겨 Debugging을 하다가 알게된 Debugging Tip
이 있어 소개합니다.

프로그램 중 Windows의 c:/windows/system32/ntdll.dll에서 프로그램이 죽은 case가 있었습니다.
물론 ntdll.dll에 문제가 아니라 우리가 작성한 program의 문제이겠지만,
ntdll.dll의 어떤 부분에서 죽었다는 정도의 힌트가 있다면 도움이 될 것입니다.
이런 symbol을 표시할 수 있도록 하는 Tip입니다.

일단 프로그램을 실행시키면 output window에 아래와 같은 Load정보가 나옵니다.
'Program.exe': Loaded 'D:\project\program\Debug\program.exe', Symbols loaded.
'Program.exe': Loaded 'C:\WINDOWS\system32\ntdll.dll'
'Program.exe': Loaded 'C:\WINDOWS\system32\kernel32.dll'
'Program.exe': Loaded 'C:\WINDOWS\system32\setupapi.dll'
'Program.exe': Loaded 'C:\WINDOWS\system32\advapi32.dll'

이중 내 프로그램이라면 Symbols loaded라고 나옵니다.
이런 symbol정보는 컴파일 후 생성된 파일인 pdb파일에서 가져오는 것입니다. 
그런데 Windows가 가지고 있는 dll들이 load될 때는 이런 pdb파일이 없기 때문에 symbol정보를 load할 수 없습니다.
결국 내가 작성해서 컴파일한 파일에서만 symbol정보를 이용할 수 있게 됩니다.

이렇게 OS의 symbol이 없는 상태에서 오류가 났을 경우의 예를 보겠습니다.
* call stack tree :
ntdll.dll!7c942b9f()
[Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll]
ntdll.dll!7c942b9f()
kernel32.dll!7c802440()
kernel32.dll!7c802402()
kernel32.dll!7c802455()
program.exe!CPortManager::SendThreadProc(void * pThis=0x01159dd8) Line 287 + 0xa bytes C++
kernel32.dll!7c80b713()
program.exe!_unlock(int locknum=11962888) Line 376 C

ntdll.dll에서 오류가 났다는 것은 알겠는데 좀 더 자세한 정보는 symbol이 load되지 않아 알 수 없다고 나옵니다.

MS에서는 이런 Kernel, System등에 사용하는 dll들의 pdb를 Symbol server에서 제공하고 있습니다.
이제 symbol Server를 사용하여 Symbol load하도록 하겠습니다.

1. VS2008 > tools > option > debugging > symbols 로 갑니다.
2. symbol file(.pdb) location에 http://msdl.microsoft.com/download/symbols를 추가해줍니다.
3. Cache symbols from ..... 에 내가 원하는 폴더를 만들어서 setting합니다.
저는 C:\Program Files\Microsoft Visual Studio 9.0\symbols 으로 setting했습니다.
이제 다 되었습니다.

프로그램을 실행시키면 output window에 아래와 같이 symbol이 load되는 것을 볼 수 있습니다.
(처음 load시에는 웹에서 download받아야 하기 때문에 엄청나게 느릴 수 있습니다.
하지만 cache folder에 저장되기 때문에 다음번 부터는 속도에 큰 지장을 주지는 않습니다.)
'Program.exe': Loaded 'D:\project\LGNPST\Program\Debug\Program.exe', Symbols loaded.
'Program.exe': Loaded 'C:\WINDOWS\system32\ntdll.dll', Symbols loaded (source information stripped).
'Program.exe': Loaded 'C:\WINDOWS\system32\kernel32.dll', Symbols loaded (source information stripped).
'Program.exe': Loaded 'C:\WINDOWS\system32\setupapi.dll', Symbols loaded (source information stripped).
'Program.exe': Loaded 'C:\WINDOWS\system32\advapi32.dll', Symbols loaded (source information stripped).
'Program.exe': Loaded 'C:\WINDOWS\system32\rpcrt4.dll', Symbols loaded (source information stripped).

이제 오류가 날 때에도 call stack에 자세한 symbol 정보가 나오게 됩니다.
ntdll.dll!_RtlDeactivateActivationContextUnsafeFast@4() + 0x419c2 bytes
kernel32.dll!_SleepEx@8() + 0xa0 bytes
kernel32.dll!_SleepEx@8() + 0x62 bytes
kernel32.dll!_Sleep@4() + 0xf bytes
Program.exe!CPortManager::SendThreadProc(void * pThis=0x01159e18) Line 284 + 0xa bytes C++
kernel32.dll!_BaseThreadStart@8() + 0x37 bytes

반응형

+ Recent posts