1.气泡提示
int flag;
BOOL CToolBallDlg::OnInitDialog()
{
.........................................
// TODO: Add extra initialization here
Flags = TTF_TRANSPARENT | TTF_SUBCLASS;
ToolTip(GetDlgItem(IDC_BUTTON1)->m_hWnd,"Button1",RGB(255,255,255),RGB(0,0,0));
ToolTip(GetDlgItem(IDC_BUTTON2)->m_hWnd,"Button2",RGB(255,255,255),RGB(0,0,0));
return TRUE; // return TRUE unless you set the focus to a control
}
void CToolBallDlg::ToolTip(HWND hWnd,char *Text,COLORREF clBackCol,COLORREF clTextCol)
{
HWND hWndToolTip;
TOOLINFOW ti;
wchar_t str[256];
hWndToolTip=CreateWindow(TOOLTIPS_CLASS,
NULL,
WS_POPUP|TTS_NOPREFIX|0x40|
TTS_ALWAYSTIP,
0, 0, 0, 0,
hWnd,
0,
AfxGetApp()->m_hInstance,
NULL);
if(hWndToolTip!=0)
{
::SetWindowPos(hWndToolTip,HWND_TOPMOST,0,0,0,0,SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOSIZE);
memset(&ti,0,sizeof(ti));
ti.cbSize = sizeof(ti);
ti.uFlags = Flags;
ti.hwnd = hWnd;
MultiByteToWideChar(CP_ACP,0,Text,-1,str,256);
ti.lpszText = str;
//ti.rect = this->GetClientRect();
this->GetClientRect(&(ti.rect));
::SendMessage(hWndToolTip,TTM_ADDTOOLW,0,(LPARAM)&ti);
}
}
2.检测CPU主频
DWORD __cdecl GetCPUFrequency(void) //MHz
{
LARGE_INTEGER CurrTicks, TicksCount;
__int64 iStartCounter, iStopCounter;
DWORD dwOldProcessP = GetPriorityClass(GetCurrentProcess());
DWORD dwOldThreadP = GetThreadPriority(GetCurrentThread());
SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
QueryPerformanceFrequency(&TicksCount);
QueryPerformanceCounter(&CurrTicks);
TicksCount.QuadPart /= 16;
TicksCount.QuadPart += CurrTicks.QuadPart;
_asm rdtsc
_asm mov DWORD PTR iStartCounter, EAX
_asm mov DWORD PTR (iStartCounter+4), EDX
while(CurrTicks.QuadPart<TicksCount.QuadPart)
QueryPerformanceCounter(&CurrTicks);
_asm rdtsc
_asm mov DWORD PTR iStopCounter, EAX
_asm mov DWORD PTR (iStopCounter + 4), EDX
SetThreadPriority(GetCurrentThread(), dwOldThreadP);
SetPriorityClass(GetCurrentProcess(), dwOldProcessP);
return (DWORD)((iStopCounter-iStartCounter)/62500);
}
3.对话框中创建视图
CCreateContext pContext;
CWnd* pFrameWnd = this;
pContext.m_pCurrentDoc = new CMyDocument;
pContext.m_pNewViewClass = RUNTIME_CLASS(CMyVw);
CMyVw *pView =(CMyVw *)((CFrameWnd*)pFrameWnd)->CreateView(&pContext);
pView->ShowWindow(SW_NORMAL);
CRect rectWindow;
GetWindowRect(rectWindow);
rectWindow.right += 15;
rectWindow.top -= 10;
pView->MoveWindow(rectWindow);
/**
* Steps:
* 1. 创建一个视图类 (最好使用类向导)
* 2. 创建一个文档类 (最好使用类向导)
* 3. 加上面的代码到你的对话框的OnInitial中
*
* CMyVw - 任意继承CView的类
* CMyDocument - 任意继承CDocument的类
*
4.屏幕变暗
void OnGray()
{
HDC hdc;
int SCRWidth,SCRHeight;
if(m_Bool)
{
BYTE bybits[] = {0x55, 0x0, 0xAA, 0x0,
0x55, 0x0, 0xAA, 0x0,
0x55, 0x0, 0xAA, 0x0,
0x55, 0x0, 0xAA, 0x0};
hBitmap = ::CreateBitmap(8, 8, 1, 1, bybits);
hBrush = ::CreatePatternBrush(hBitmap);
hdc = ::GetDC(NULL);
SCRWidth = ::GetSystemMetrics(SM_CXSCREEN);
SCRHeight = ::GetSystemMetrics(SM_CYSCREEN);
::SelectObject(hdc,hBrush);
//0xA000C9
::PatBlt(hdc,0,0,SCRWidth,SCRHeight,0xA000C9);
::DeleteObject(hBrush);
::ReleaseDC(0, hdc);
}
else
::InvalidateRect(NULL, 0, 1);
m_Bool ? m_Gray.SetWindowText("恢复"):m_Gray.SetWindowText("屏幕变暗");
m_Bool = !(m_Bool);
}
5.枚举网上邻居
下面的代码通过第归处理枚举所有的网络邻居
BOOL CMyApp::EnumerateNetHood( LPNETRESOURCE lpnr )
{
DWORD dwRet, dwRetEnum;
HANDLE hEnum;
DWORD cbBuffer = 16384;
DWORD cEntries = 0xFFFFFFFF;
LPNETRESOURCE lpnrLocal;
DWORD i;
CString str;
int nLevel = -1;
CString strDisplayName;
CString strTrueName;
dwRet = WNetOpenEnum( RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, lpnr, &hEnum );
if( dwRet == WN_FUNCTION_BUSY || dwRet == ERROR_BAD_NET_NAME )
return TRUE;
if( dwRet != NO_ERROR )
{
AfxMessageBox("WNetOpenEnum" );
return FALSE;
}
do
{
lpnrLocal = (LPNETRESOURCE)GlobalAlloc( GPTR, cbBuffer );
dwRetEnum = WNetEnumResource( hEnum, &cEntries, lpnrLocal, &cbBuffer);
if( dwRetEnum == NO_ERROR)
{
for( i = 0; i < cEntries; i++ )
{
// 只搜索网络提供者为"Microsoft Network"的资源
str="Microsoft Network";
int nCmpNo = lstrcmpi( (LPCTSTR)lpnrLocal[i].lpProvider, (LPCTSTR)str );
if( nCmpNo )
continue;
if( RESOURCEUSAGE_CONTAINER == ( lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER ) )
{
nLevel = -1;
switch( lpnrLocal[i].dwDisplayType ) {
case RESOURCEDISPLAYTYPE_NETWORK: // 整个网络
nLevel = 0;
strDisplayName="整个网络(*)";
strTrueName = "*";
break;
case RESOURCEDISPLAYTYPE_DOMAIN: // 工作组
nLevel = 1;
strTrueName="-工作组";
strDisplayName.Format( "%s%s", lpnrLocal[i].lpRemoteName, strTrueName );
strTrueName = lpnrLocal[i].lpRemoteName;
break;
case RESOURCEDISPLAYTYPE_SERVER: // 计算机
nLevel = 2;
// 加 2 是为去掉前缀"//"
strDisplayName.Format( "%s", lpnrLocal[i].lpRemoteName + 2 );
strTrueName = strDisplayName;
break;
}
ASSERT( nLevel != -1 );
NewInfoNetHood( nLevel, strTrueName, strDisplayName );
if( !EnumerateNetHood( &lpnrLocal[i] ) )
return FALSE;
}
}
}
else
{
if( dwRetEnum != ERROR_NO_MORE_ITEMS )
{
AfxMessageBox("WNetEnumResource" );
return FALSE;
}
}
}
while( dwRetEnum != ERROR_NO_MORE_ITEMS );
GlobalFree( (HGLOBAL)lpnrLocal );
dwRet = WNetCloseEnum( hEnum );
if( dwRet != NO_ERROR )
{
AfxMessageBox("WNetCloseEnum" );
return FALSE;
}
return TRUE;
}
BOOL WINAPI EnumerateFunc(HWND hwnd,
HDC hdc,
LPNETRESOURCE lpnr)
{
DWORD dwResult, dwResultEnum;
HANDLE hEnum;
DWORD cbBuffer = 16384; // 16K is a good size
DWORD cEntries = -1; // enumerate all possible entries
LPNETRESOURCE lpnrLocal; // pointer to enumerated structures
DWORD i;
//
// Call the WNetOpenEnum function to begin the enumeration.
//
dwResult = WNetOpenEnum(RESOURCE_GLOBALNET, // all network resources
RESOURCETYPE_ANY, // all resources
0, // enumerate all resources
lpnr, // NULL first time the function is called
&hEnum); // handle to the resource
if (dwResult != NO_ERROR)
{
//
// Process errors with an application-defined error handler.
//
NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetOpenEnum");
return FALSE;
}
//
// Call the GlobalAlloc function to allocate resources.
//
lpnrLocal = (LPNETRESOURCE) GlobalAlloc(GPTR, cbBuffer);
if (lpnrLocal == NULL)
return FALSE;
do
{
//
// Initialize the buffer.
//
ZeroMemory(lpnrLocal, cbBuffer);
//
// Call the WNetEnumResource function to continue
// the enumeration.
//
dwResultEnum = WNetEnumResource(hEnum, // resource handle
&cEntries, // defined locally as -1
lpnrLocal, // LPNETRESOURCE
&cbBuffer); // buffer size
//
// If the call succeeds, loop through the structures.
//
if (dwResultEnum == NO_ERROR)
{
for(i = 0; i < cEntries; i++)
{
// Call an application-defined function to
// display the contents of the NETRESOURCE structures.
//
DisplayStruct(hdc, &lpnrLocal[i]);
// If the NETRESOURCE structure represents a container resource,
// call the EnumerateFunc function recursively.
if(RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage
& RESOURCEUSAGE_CONTAINER))
if(!EnumerateFunc(hwnd, hdc, &lpnrLocal[i]))
TextOut(hdc, 10, 10, "EnumerateFunc returned FALSE.", 29);
}
}
// Process errors.
//
else if (dwResultEnum != ERROR_NO_MORE_ITEMS)
{
NetErrorHandler(hwnd, dwResultEnum, (LPSTR)"WNetEnumResource");
break;
}
}
//
// End do.
//
while(dwResultEnum != ERROR_NO_MORE_ITEMS);
//
// Call the GlobalFree function to free the memory.
//
GlobalFree((HGLOBAL)lpnrLocal);
//
// Call WNetCloseEnum to end the enumeration.
//
dwResult = WNetCloseEnum(hEnum);
if(dwResult != NO_ERROR)
{
//
// Process errors.
//
NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetCloseEnum");
return FALSE;
}
return TRUE;
}
7.获取汉字类码
String s("你");
unsigned short H,L;
H=(unsigned short)(s[1])<<8;
L=(unsigned char)(s[2]);
int n=H+L;
8.sscanf函数的高级用法
sscanf是一个很好用的函数,利用它可以从字符串中取出整数、浮点数和字符串等等。它的使用方法简单,特别对于整数和浮点数来说。但新
手可能并不知道处理字符串时的一些高级用法,这里做个简要说明吧。
1. 常见用法。
以下是引用片段:
char str[512] = {0};
sscanf("123456 ", "%s", str);
printf("str=%s/n", str);
2. 取指定长度的字符串。如在下例中,取最大长度为4字节的字符串。
以下是引用片段:
sscanf("123456 ", "%4s", str);
printf("str=%s/n", str);
3. 取到指定字符为止的字符串。如在下例中,取遇到空格为止字符串。
以下是引用片段:
sscanf("123456 abcdedf", "%[^ ]", str);
printf("str=%s/n", str);
4. 取仅包含指定字符集的字符串。如在下例中,取仅包含1到9和小写字母的字符串。
以下是引用片段:
sscanf("123456abcdedfBCDEF", "%[1-9a-z]", str);
printf("str=%s/n", str);
5. 取到指定字符集为止的字符串。如在下例中,取遇到大写字母为止的字符串。
以下是引用片段:
sscanf("123456abcdedfBCDEF", "%[^A-Z]", str);
printf("str=%s/n", str);
9.检测当前操作系统是中文还是英文
UINT LanID = GetSystemDefaultLangID();
if (PRIMARYLANGID(LanID)==LANG_CHINESE && SUBLANGID(LanID)==SUBLANG_CHINESE_SIMPLIFIED);// 简体中文Windows
10.文件树状显示
int FillTree(CTreeCtrl &tcLibTree, BOOL bCatalogOnly/* = FALSE*/,HTREEITEM hParent/* = TVI_ROOT*/)
{
if (hParent == TVI_ROOT)
{//这里填充的是根,修改成你的目录即可。
LPTSTR szPath = new TCHAR[MAX_PATH];
ZeroMemory(szPath, MAX_PATH);
::GetModuleFileName(NULL, szPath, MAX_PATH);
::PathRemoveFileSpec(szPath);
::PathCombine(szPath, szPath, _T("Library//"));
HTREEITEM hSelectedItem = tcLibTree.InsertItem(_T("元件库"));
tcLibTree.SetItemData(hSelectedItem, (DWORD_PTR)szPath);
tcLibTree.SelectItem(hSelectedItem);
return FillTree(tcLibTree, bCatalogOnly, hSelectedItem);
}
TCHAR szFindPath[MAX_PATH];
LPCTSTR szPath = (LPCTSTR)tcLibTree.GetItemData(hParent);
StrCpy(szFindPath, szPath);
::PathCombine(szFindPath, szPath, _T("*.*"));
CFileFind ffLib;
BOOL bFinded = ffLib.FindFile(szFindPath);
while (bFinded)
{
bFinded = ffLib.FindNextFile();
//CString strFile = ;
CString strFile = ffLib.GetFilePath();
CString strFileName = ffLib.GetFileName();
if (strFileName == _T(".") || strFileName == _T(".."))
{
continue;
}
if (bCatalogOnly && !::PathIsDirectory(strFile))
continue;
::PathRemoveExtension(strFileName.GetBuffer(MAX_PATH));
HTREEITEM hThis = tcLibTree.InsertItem(strFileName, hParent);
if (hThis)
{
LPTSTR szFile = new TCHAR[strFile.GetLength() + 1];
StrCpy(szFile, strFile);
tcLibTree.SetItemData(hThis, (DWORD_PTR)szFile);
if (::PathIsDirectory(strFile))
{
FillTree(tcLibTree, bCatalogOnly, hThis);
}
}
}
return 0;
}
11.启用禁用网卡
/*****************************************************************************
演示如何编程实现启用禁用网卡
Mady By ZwelL
2004.7.29
zwell@sohu.com
*****************************************************************************/
#include <windows.h>
#include <setupapi.h>
#include <tchar.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"setupapi.lib")
BOOL DisableNetInterface(bool bStatus)
{
IN LPTSTR HardwareId ;
//硬件ComponentId,注册表地址:system/currentcontrolset/class/{4D36E972-E325-11CE-BFC1-08002BE10318}/0000
HardwareId="PCI//VEN_10EC&DEV_8139&SUBSYS_813910EC" ;
DWORD NewState ;
if(bStatus)
{
NewState=DICS_DISABLE ;
//禁用
}
else
{
NewState=DICS_ENABLE ;
//启用
}
//调用ddk函数,来禁用网卡
DWORD i,err ;
BOOL Found=false ;
HDEVINFO hDevInfo ;
SP_DEVINFO_DATA spDevInfoData ;
//访问系统的硬件库
hDevInfo=SetupDiGetClassDevs(NULL,"PCI",NULL,DIGCF_ALLCLASSES|DIGCF_PRESENT);
if(hDevInfo==INVALID_HANDLE_VALUE)
{
printf("访问系统硬件出错!");
return false ;
}
//枚举硬件,获得需要的接口
spDevInfoData.cbSize=sizeof(SP_DEVINFO_DATA);
for(i=0;SetupDiEnumDeviceInfo(hDevInfo,i,&spDevInfoData);i++)
{
DWORD DataT ;
LPTSTR p,buffer=NULL ;
DWORD buffersize=0 ;
//获得硬件的属性值
while(!SetupDiGetDeviceRegistryProperty(
hDevInfo,
&spDevInfoData,
SPDRP_HARDWAREID,
&DataT,
(PBYTE)buffer,
buffersize,
&buffersize))
{
if(GetLastError()==ERROR_INVALID_DATA)
{
//不存在HardwareID. Continue.
break ;
}
else if(GetLastError()==ERROR_INSUFFICIENT_BUFFER)
{
//buffer size不对.
if(buffer)
LocalFree(buffer);
buffer=(char*)LocalAlloc(LPTR,buffersize);
}
else
{
//未知错误
goto cleanup_DeviceInfo ;
}
}
if(GetLastError()==ERROR_INVALID_DATA)
continue ;
//比较,找到和网卡ID相同的项
for(p=buffer;*p&&(p<&buffer[buffersize]);p+=lstrlen(p)+sizeof(TCHAR))
{
if(!_tcscmp(HardwareId,p))
{
//找到网卡
Found=TRUE ;
break ;
}
}
if(buffer)
LocalFree(buffer);
//如果相等
if(Found)
{
//禁用该设备
SP_PROPCHANGE_PARAMS spPropChangeParams ;
spPropChangeParams.ClassInstallHeader.cbSize=sizeof(SP_CLASSINSTALL_HEADER);
spPropChangeParams.ClassInstallHeader.InstallFunction=DIF_PROPERTYCHANGE ;
spPropChangeParams.Scope=DICS_FLAG_GLOBAL ;
spPropChangeParams.StateChange=NewState ;
//禁用:DICS_DISABLE,DICS_ENABLE启用
//
if(!SetupDiSetClassInstallParams(hDevInfo,&spDevInfoData,(SP_CLASSINSTALL_HEADER*)&spPropChangeParams,sizeof
(spPropChangeParams)))
{
DWORD errorcode=GetLastError();
}
if(!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE,hDevInfo,&spDevInfoData))
{
DWORD errorcode=GetLastError();
}
switch(NewState)
{
case DICS_DISABLE :
printf("成功禁用网络!");
break ;
case DICS_ENABLE :
printf("成功启用网络!");
break ;
}
break ;
}
}
//退出时,清理工作环境
cleanup_DeviceInfo :
err=GetLastError();
SetupDiDestroyDeviceInfoList(hDevInfo);
SetLastError(err);
return true ;
}
void usage(char *exefile)
{
printf("Usage:%s [-e|-d]/r/n", exefile);
printf("/t-e: Enable the network card./r/n");
printf("/t-d: Disable the network card./r/n");
exit(0);
}
int main(int argc,char**argv)
{
if(argc<2)
usage(argv[0]);
if(!DisableNetInterface((strstr(argv[1],"-d")>0?TRUE:FALSE)))
printf("对网卡操作失败!");
return 0;
}
//对于XP的系统 一定要提升权限
BOOL EnablePriv()
{
HANDLE hToken;
if ( OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES,&hToken) )
{
TOKEN_PRIVILEGES tkp;
LookupPrivilegeValue( NULL,SE_DEBUG_NAME,&tkp.Privileges[0].Luid );//修改进程权限
tkp.PrivilegeCount=1;
tkp.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges( hToken,FALSE,&tkp,sizeof tkp,NULL,NULL );//通知系统修改进程权限
return( (GetLastError()==ERROR_SUCCESS) );
}
return TRUE;
}