python 编写的windows实用演示程序 使用到C语言风格,同时对Windows消息机制进行演示

因为内容较多 涉及知识点也多一些 但是具体使用时分开在几个文件 同时展示C语言的结构类型如何在python中定义与使用。为了便于区别 我定义的数据文件最后都带有一个数字1,涉及第三方库较少 ,以便灵活使用Windows自带的很多api函数功能,可以根据自己的需求 修改不同的消息处理,供初学者参考

该框架涉及4个文件

1、主文件                                  名称:          创建窗口程序规范版01.py

2、保存全局变量的文件            名称:          Globalvariable1.py

3、定义结构类型文件                名称:          structure1.py

4、调用api函数的描述数据        名称:          systemMetricsDic1.py

由此演示一个简单Windows程序 尽量让数据分散在多个文件 这样规模变大时候逐渐在各个文件中增加数据,对于注释,可以忽略,那是不断验证程序功能用到的,下面给出实现代码与结果演示:

1----创建窗口程序规范版01.py:

import datetime
import sys
import structure1
from winsound import PlaySound
import winsound
import win32gui
import win32con
import ctypes
# import cv2
import win32api
import ctypes.wintypes
from threading import Thread
#引入systemMetrics函数数据
import systemMetricsDic1
import time
user32 = ctypes.windll.user32
gdi32=ctypes.windll.gdi32
import Globalvariable1
winmm=ctypes.windll.LoadLibrary(r"./winmm.dll")
debug=True
SND_FILENAME=0x20000
SND_ASYNC=0x01
#--------因为python是解释型语言 所以回调函数最先创建----------------------------------------
# cv2.namedWindow("img",cv2.WINDOW_NORMAL)  #cv2.WINDOW_NORMAL窗口大小可变
# cvHwnd= win32gui.FindWindow(None, "img")
#
# print(cvHwnd)
keyDisplay=True
closeDisplay=False

pStringBuffer= ctypes.create_string_buffer(b"Hello",Globalvariable1.stringBufferSize)
def LOWORD(x):
    return x & 0xffff
def HOWORD(x):
    return (x>>16) & 0xffff
def windowProc(hwnd, msg, wParam, lParam):
    #-----------使用if风格的回调函数 显示立体边框------------------
    # if msg == win32con.WM_DESTROY:
    #     win32gui.PostQuitMessage(0)
    #     return 0
    # else:
    #     print("消息编号",msg)
    #     print("w参数",wPrame)
    #     print("l参数",lParam)
    # return win32gui.DefWindowProc(hwnd, msg, wParam, lParam)

    #-----------使用这种语句 显示老式风格的边框-----------------
    match msg:
        case win32con.WM_CREATE:
            if debug:
                print("窗口第一次创建\n")
                PlaySound("./hello.wav",winsound.SND_ASYNC)

            hdc = user32.GetDC(hwnd)

            #------------自定义的结构类型--------------------
            tm = structure1.TEXTMETRIC()
            #采用引用类型 以便能修改传入的参数
            gdi32.GetTextMetricsA(hdc, ctypes.byref(tm))

            Globalvariable1.global_cxChar = tm.tmAveCharWidth
            Globalvariable1.global_cyChar = tm.tmHeight + tm.tmExternalLeading
            #tmPitchAndFamily低位为1 变宽字体 否则为等宽字体
            if tm.tmPitchAndFamily & 0x1:
                Globalvariable1.global_cxCaps = 1.5*Globalvariable1.global_cxChar
            else:
                Globalvariable1.global_cxCaps = 1 * Globalvariable1.global_cxChar


            user32.ReleaseDC(hwnd, hdc)
            #----------------任务1开始一--------------------
            # cv2.namedWindow("img", cv2.WINDOW_NORMAL)  # cv2.WINDOW_NORMAL窗口大小可变
            # cvHwnd = win32gui.FindWindow(None, "img")
            # cancelWindowCaptionBar(cvHwnd)
            # retValue = user32.SetParent(cvHwnd, hwnd)
            # rectParentClient = win32gui.GetClientRect(hwnd)
            # user32.MoveWindow(cvHwnd, 0, 0, rectParentClient[2], rectParentClient[3], True)

            # cap=cv2.VideoCapture(0)
            # img = cv2.imread("test.png")
            # global closeDisplay
            # while keyDisplay:
            #    success,img=cap.read()
            #    cv2.imshow("img", img)
            #    kk=cv2.waitKey(1)
            #    if kk & 0XFF==ord('q'):
            #        break
            #    if closeDisplay==True:
            #        break
            #        sys.exit()
            #        cap.release()
            #        cv2.destroyAllWindows()
            #-----任务1结束---------------
            return 0


        case win32con.WM_PAINT:
            #产生WN_PAINT消息的的情况  客户区被隐藏又重现 用户改变窗口大小 调用ScrollWindow或者ScrollDC函数 调用InvalidateRect或InvalidateRgn函数
            #擦除覆盖的消息框或者对话框 下拉菜单出现与消失 显示工具提示

            #收到该消息 必须使无效区域变为有效区域才返回 不然Windows会一直发生WM_PAINT消息 直到区域有效
            # print("接收到绘制消息",msg)
            hdc,ps=win32gui.BeginPaint(hwnd)
            #hdc只是客户区无效区域
            # print(ps)
            # hdc=win32gui.GetDC(hwnd)
            print("字符宽度:",Globalvariable1.global_cxChar)
            systemMetricsDicObject=systemMetricsDic1.systemMetrics()
            if Globalvariable1.global_cxChar>0:
                pass

                for i in range(systemMetricsDicObject.leng()):
                    #输出索引常量名
                    gdi32.TextOutW(hdc,0,Globalvariable1.global_cyChar*i,systemMetricsDicObject.dicByIndex[i]["label"],len(systemMetricsDicObject.dicByIndex[i]["label"]))
                    #输出索引常量描述  x位置向右偏移约Globalvariable1.global_cxCaps*22
                    gdi32.TextOutW(hdc, Globalvariable1.global_cxCaps*44, Globalvariable1.global_cyChar * i,
                                   systemMetricsDicObject.dicByIndex[i]["describle"],
                                   len(systemMetricsDicObject.dicByIndex[i]["describle"]))
                    value=user32.GetSystemMetrics(systemMetricsDicObject.dicByIndex[i]["index"])
                    print("输出得到的结果:",value)
                    #右对齐
                    gdi32.SetTextAlign(hdc,win32con.TA_RIGHT|win32con.TA_TOP)
                    gdi32.TextOutW(hdc,Globalvariable1.global_cxCaps*44+40*Globalvariable1.global_cxChar,Globalvariable1.global_cyChar * i,str(value),len(str(value)))
                    #恢复左对齐输出
                    gdi32.SetTextAlign(hdc, win32con.TA_LEFT | win32con.TA_TOP)


            rect=win32gui.GetClientRect(hwnd)
            win32gui.DrawTextW(hdc,"hello中国",len("hello中国"),rect,win32con.DT_SINGLELINE | win32con.DT_CENTER | win32con.DT_VCENTER)
            # win32gui.ReleaseDC(hwnd,hdc)
            #----------------任务1
            # user32.MoveWindow(cvHwnd, 0, 0, rect[2], rect[3], True)

            win32gui.EndPaint(hwnd,ps)
            return 0
        case win32con.WM_NCPAINT:
            print("这是非客户区消息")

        case win32con.WM_SIZE:
            print("测试一下初始化Globalvariable1.global_cxChar的字体信息:",Globalvariable1.global_cxChar)

            if debug:
                print("如果是第一个WM_SIZE消息,通常由调用ShowWindow函数产生")
                print("你改变了窗口尺寸,消息编号是:", msg, " ", hex(msg), "wParam的值是:", wParam, "  lParam的值是:", lParam)
                print("wParam的值是窗口状态")
                if wParam==win32con.SIZE_RESTORED:
                    print("  窗口为创建时的尺寸:SIZE_RESTORED:",win32con.SIZE_RESTORED)
                if wParam==win32con.SIZE_MINIMIZED:
                    print("  窗口最小化:SIZE_MINIMIZED:",win32con.SIZE_MINIMIZED)
                if wParam==win32con.SIZE_MAXIMIZED:
                    print("  窗口最大化:SIZE_MAXIMIZED:",win32con.SIZE_MAXIMIZED)
                if wParam==win32con.SIZE_MAXSHOW:
                    print("  当其他某个窗口还原到原来的大小时,消息将发送到所有弹出窗口:SIZE_MAXSHOW:",win32con.SIZE_MAXSHOW)
                if wParam==win32con.SIZE_MAXHIDE:
                    print("  当其他某个窗口最大化时,消息将发送到所有弹出窗口:SIZE_MAXHIDE:",win32con.SIZE_MAXHIDE)
                print("lParam的值是窗口尺寸数值:")
                print("  lParam低位窗口客户区新宽度:",LOWORD(lParam))
                print("  lParam高位窗口客户区新宽度:", HOWORD(lParam))
            return 0
        case win32con.WM_SHOWWINDOW:
            if debug:
                print("收到一个WM_SHOWWINDOW显示窗口消息,通常由调用ShowWindow函数产生")
                return 0
        case win32con.WM_SYSCOMMAND:
            if debug:
                print("注意!!!收到一个系统命令,通常不要返回,继续让消息传给系统处理:否则属于屏蔽系统命令,WM_SYSCOMMAND消息编号是:",msg," ",hex(msg),"wParam的值是:",wParam,"  lParam的值是:",lParam)




        case win32con.WM_LBUTTONDOWN:
            if debug:
                print("你单击了鼠标左键,消息编号是:",msg," ",hex(msg),"wParam的值是:",wParam,"  lParam的值是:",lParam)
            return 0
        case win32con.WM_RBUTTONDOWN:
            if debug:
                print("你单击了鼠标右键,消息编号是:",msg," ",hex(msg),"wParam的值是:",wParam,"  lParam的值是:",lParam)
            return 0
        case win32con.WM_MOUSEMOVE:
            if debug:
                pass
                # print("你正在移动鼠标,消息编号是:",msg," ",hex(msg),"wParam的值是:",wParam,"  lParam的值是:",lParam)
            return 0
        case win32con.WM_MBUTTONDOWN:
            if debug:
                print("你单击了鼠标中键,消息编号是:",msg," ",hex(msg),"wParam的值是:",wParam,"  lParam的值是:",lParam)
            return 0
        case win32con.WM_LBUTTONDBLCLK:
            if debug:
                print("你双击了鼠标左键,消息编号是:",msg," ",hex(msg),"wParam的值是:",wParam,"  lParam的值是:",lParam)
            return 0
        case win32con.WM_KEYDOWN:
            if debug:
                print("你按下了键盘键,消息编号是:", msg, " ", hex(msg), "wParam的值是:", wParam, "  lParam的值是:", lParam)
            return 0
        case  win32con.WM_DESTROY:
            keyDisplay==False
            closeDisplay=True
            cv2.destroyAllWindows()
            win32gui.PostQuitMessage(0)
            if debug:
               print("程序终止")
            return 0

    return win32gui.DefWindowProc(hwnd, msg, wParam, lParam)


def cancelWindowCaptionBar(hwnd):

    dwStyle = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE)
    dwStyle ^= win32con.WS_MINIMIZEBOX  # 设置窗体取消最小化按钮
    dwStyle ^= win32con.WS_MAXIMIZEBOX  # 设置窗体取消最大化按钮
    dwStyle ^= win32con.WS_DLGFRAME  # 设置窗体取消标题栏边框
    # dwStyle &= ~(win32con.WS_SIZEBOX)     #取消调整大小
    win32api.SetWindowLong(hwnd, win32con.GWL_STYLE, dwStyle)  # 设置新的风格

def threadFunc(name, sec):
    print('---开始---', name, '时间', datetime.datetime.now())
    time.sleep(sec)
    print('***结束***', name, '时间', datetime.datetime.now())
    img1=cv2.imread("test.png")
    cv2.imshow("img1",img1)
    cv2.waitKey(0)

className = 'MyWindowClass'
#---------第一步   初始化类结构-python版本和C语言版本有一定的不同 某些域没有cbClsExtra-----------------------------------------
#---------窗口类的作用就是定义窗口的一般性特征 或者通用特征
wndClass = win32gui.WNDCLASS()
wndClass.cbWndExtra=0
wndClass.style = win32con.CS_HREDRAW | win32con.CS_VREDRAW | win32con.CS_DBLCLKS  #每当窗口水平方向或垂直方向尺寸发生改变后 要完全刷新窗口
wndClass.lpfnWndProc = windowProc                           #这个过程要处理基于这个窗口类创建的所有窗口的全部消息  使用函数名 实际引用提供指向函数的指针
wndClass.hInstance = win32gui.GetModuleHandle(None)         #程序的实例句柄
wndClass.hCursor = win32gui.LoadCursor(None, win32con.IDC_ARROW)    #使用预定义图标 第一个参数为None  使用自定义图片 第一个参数为程序的实例句柄
wndClass.hbrBackground =  win32con.COLOR_WINDOW     #win32gui.GetStockObject(win32con.WHITE_BRUSH) 或者获取图像对象#将窗口客户区边界设置为指定颜色
wndClass.lpszClassName = className

#--------第二步  注册类---------------------------------------------
wndClassAtom = win32gui.RegisterClass(wndClass)   #因为python中变量名就是结构体的地址 无须像C语言使用取地址运算符&

if(wndClassAtom==0):
        print("注册失败")
        sys.exit(0)
# print("注册结果",wndClassAtom)
#-------第三步  创建程序主窗口-------------------------------------------------
hwnd = win32gui.CreateWindow(className, "我的窗口", win32con.WS_OVERLAPPEDWINDOW, 100, 100, 500, 500, None, None, win32gui.GetModuleHandle(None), None)

#---------第四步 显示并更新窗口
win32gui.ShowWindow(hwnd, win32con.SW_SHOW) #产生一个WM_SIZE消息
win32gui.UpdateWindow(hwnd)  #产生一个WM_PAINT消息

#-----------img窗口  取消最大 最小按钮---------------------------------
# retValue=user32.SetParent(cvHwnd,hwnd)
# rectParentClient=win32gui.GetClientRect(hwnd)
# print("父窗口:",rectParentClient)
# dwStyle = win32api.GetWindowLong(cvHwnd, win32con.GWL_STYLE)
#
# print("窗口风格",dwStyle)
# dwStyle ^= win32con.WS_MINIMIZEBOX    #设置窗体取消最小化按钮
# dwStyle ^= win32con.WS_MAXIMIZEBOX    #设置窗体取消最大化按钮
# dwStyle ^= win32con.WS_DLGFRAME       #设置窗体取消标题栏边框
#
#
# # dwStyle &= ~(win32con.WS_SIZEBOX)     #取消调整大小
# win32api.SetWindowLong(cvHwnd, win32con.GWL_STYLE, dwStyle)  #设置新的风格
# # user32.SetWindowLongA(cvHwnd, win32con.GWL_STYLE, dwStyle)  #设置新的风格
# #去除窗口标题栏 大小化按钮
# user32.MoveWindow(cvHwnd,0,0,rectParentClient[2],rectParentClient[3],True)
# img = cv2.imread("test1.jpeg")
# cv2.imshow("img", img)


#------------------------------------
#------------多线程------------------------
# 创建 Thread 实例
# t1 = Thread(target=threadFunc, args=('第一个线程', 1))
# t2 = Thread(target=threadFunc, args=('第二个线程', 2))
#
# # 启动线程运行
# t1.start()
# t2.start()


# 等待所有线程执行完毕
# t1.join()  # join() 等待线程终止,要不然一直挂起
# t2.join()

#——————————————多线程接收 ————————————————————

#-------第五步 创建消息结构体并建立消息循环 -------------------------------
msg = ctypes.wintypes.MSG()

wParam=None
lparam=None
#手动调用一次回调函数 python调试时中不自动执行创建初始化
# windowProc(hwnd,win32con.WM_CREATE,0,0)

#-------自己使用函数调用---------------------------
user32.SendMessageA(hwnd,win32con.WM_CREATE,wParam)
hdc=user32.GetDC(hwnd)
testString="测试文字\n又是一个"
#注意 参数涉及字符串的函数可能都有ASCII版本和Unicode版本
gdi32.TextOutW(hdc,0,0,testString,len(testString))
# tm=structure1.TEXTMETRIC()
# #注意 由于要修改传入的参数 使用引用传递
# gdi32.GetTextMetricsA(hdc,ctypes.byref(tm))
# if debug:
#     print(tm.tmCharSet)
#     print("系统字体高度:",tm.tmHeight)
#     print("字体基线以上高度:",tm.tmAscent)
#     print("字体横向之间的建议空间:", tm.tmExternalLeading)
#     print("字体最宽字符的宽度:", tm.tmMaxCharWidth)
#     print("字体字符平均宽度:", tm.tmAveCharWidth)
#     Globalvariable1.global_cxChar=tm.tmAveCharWidth
#     Globalvariable1.global_cyChar=tm.tmHeight+ tm.tmExternalLeading
user32.ReleaseDC(hwnd,hdc)

#测试使用格式化函数wsprintfW
user32.wsprintfW(pStringBuffer,"this is %d test %d,%d",ctypes.c_int32(5).value,ctypes.c_int32(7).value,ctypes.c_int32(5).value)
print("缓冲字符串:",pStringBuffer)
s=""
for i in pStringBuffer:
    # print(i,end='')
    if i != b'\x00':
        s=s+i.decode('utf-8')
print(s)
    # print(i.decode('utf-8'),end="")
print("测试全局变量的Globalvariable1.global_cxChar值",Globalvariable1.global_cxChar)



#第六步 自动执行消息队列  msg由操作系统自动生成 传递给你的程序
while user32.GetMessageW(ctypes.byref(msg), None, wParam, lparam) != 0:
    user32.TranslateMessage(ctypes.byref(msg))
    user32.DispatchMessageW(ctypes.byref(msg))

2---Globalvariable1.py:

#不要想当然猜测字符大小来编写Windows程序 也不要把值定死 可以使用GetTextMetrics函数获取这一信息

global_cxChar=0   #单个字符宽度  在创建窗口是自动计算结果后保存于该全局变量
global_cyChar=0   #单个字符高度
global_cxCaps=0   #遇到等宽字体 那么global_cxCaps=global_cxChar,遇到变宽字体 大约为1.5倍于global_cxChar


stringBufferSize=512

3-----structure1.py:

import ctypes

HANDLE = ctypes.c_void_p

HDC = HANDLE

LONG = ctypes.c_long
BOOL = ctypes.c_long
BYTE = ctypes.c_byte
WCHAR = ctypes.c_wchar

class RECT(ctypes.Structure):
    _fields_ = [("left", LONG),
                ("top", LONG),
                ("right", LONG),
                ("bottom", LONG)]
tagRECT = _RECTL = RECTL = RECT

class PAINTSTRUCT(ctypes.Structure):
    _fields_=[("hdc",HDC),
              ("fErase",BOOL),
              ("rcPaint",RECT),
              ("fRestore",BOOL),
              ("fIncUpdate",BOOL),
              ("rgbReserved",BYTE * 32)]
tagPAINTSTRUCT=PAINTSTRUCT

class TEXTMETRIC(ctypes.Structure):
  _fields_=[("tmHeight",LONG),
            ("tmAscent",LONG),
            ('tmDescent',LONG),
            ('tmInternalLeading', LONG),
            ('tmExternalLeading',LONG ),
            ('tmAveCharWidth',LONG ),
            ('tmMaxCharWidth',LONG ),
            ('tmWeight',LONG ),
            ('tmOverhang',LONG ),
            ('tmDigitizedAspectX',LONG ),
            ('tmDigitizedAspectY',LONG),
            ('tmFirstChar',WCHAR),
            ('tmLastChar',WCHAR),
            ('tmDefaultChar', WCHAR),
            ('tmBreakChar',WCHAR ),
            ('tmItalic',BYTE ),
            ('tmUnderlined',BYTE ),
            ('tmStruckOut', BYTE ),
            ('tmPitchAndFamily',BYTE),
            ('tmCharSet',BYTE)]
TEXTMETRICW=PTEXTMETRICW=NPTEXTMETRICW=LPTEXTMETRICW=TEXTMETRIC

#演示 验证初始化后是否正确打印每个域的值
p=PAINTSTRUCT(1111,1)

print(p.hdc,p.fErase)

4----------systemMetricsDic1.py:

class systemMetrics:
    def __init__(self):
        self.dicByIndex = {0: {"label": "SM_CXSCREEN", "index": 0, "describle": "Screen width in pixels"},
                           "SM_CXSCREEN": {"label": "SM_CXSCREEN", "index": 0, "describle": "Screen width in pixels"},
                           1: {"label": "SM_CYSCREEN", "index": 1, "describle": "Screen height in pixels"},
                           "SM_CYSCREEN": {"label": "SM_CYSCREEN", "index": 1, "describle": "Screen height in pixels"},
                           2: {"label": "SM_CXVSCROLL", "index": 2, "describle": "Vertical scroll width"},
                           "SM_CXVSCROLL": {"label": "SM_CXVSCROLL", "index": 2, "describle": "Vertical scroll width"},
                           3: {"label": "SM_CYHSCROLL", "index": 3, "describle": "Horizontal scroll height"},
                           "SM_CYHSCROLL": {"label": "SM_CYHSCROLL", "index": 3,
                                            "describle": "Horizontal scroll height"},
                           4: {"label": "SM_CYCAPTION", "index": 4, "describle": "Caption bar height"},
                           "SM_CYCAPTION": {"label": "SM_CYCAPTION", "index": 4, "describle": "Caption bar height"},
                           5: {"label": "SM_CXBORDER", "index": 5, "describle": "Window border width"},
                           "SM_CXBORDER": {"label": "SM_CXBORDER", "index": 5, "describle": "Window border width"},
                           6: {"label": "SM_CYBORDER", "index": 6, "describle": "Window border height"},
                           "SM_CYBORDER": {"label": "SM_CYBORDER", "index": 6, "describle": "Window border height"},
                           7: {"label": "SM_CXFIXEDFRAME", "index": 7, "describle": "Dialog window frame width"},
                           "SM_CXFIXEDFRAME": {"label": "SM_CXFIXEDFRAME", "index": 7,
                                               "describle": "Dialog window frame width"},
                           8: {"label": "SM_CYFIXEDFRAME", "index": 8, "describle": "Dialog window frame height"},
                           "SM_CYFIXEDFRAME": {"label": "SM_CYFIXEDFRAME", "index": 8,
                                               "describle": "Dialog window frame height"},
                           9: {"label": "SM_CYVTHUMB", "index": 9, "describle": "Vertical scroll thumb height"},
                           "SM_CYVTHUMB": {"label": "SM_CYVTHUMB", "index": 9,
                                           "describle": "Vertical scroll thumb height"},
                           10: {"label": "SM_CXHTHUMB", "index": 10, "describle": "Horizontal scroll thumb width"},
                           "SM_CXHTHUMB": {"label": "SM_CXHTHUMB", "index": 10,
                                           "describle": "Horizontal scroll thumb width"},
                           11: {"label": "SM_CXICON", "index": 11, "describle": "Icon width"},
                           "SM_CXICON": {"label": "SM_CXICON", "index": 11, "describle": "Icon width"},
                           12: {"label": "SM_CYICON", "index": 12, "describle": "Icon height"},
                           "SM_CYICON": {"label": "SM_CYICON", "index": 12, "describle": "Icon height"},
                           13: {"label": "SM_CXCURSOR", "index": 13, "describle": "Cursor width"},
                           "SM_CXCURSOR": {"label": "SM_CXCURSOR", "index": 13, "describle": "Cursor width"},
                           14: {"label": "SM_CYCURSOR", "index": 14, "describle": "Cursor height"},
                           "SM_CYCURSOR": {"label": "SM_CYCURSOR", "index": 14, "describle": "Cursor height"},
                           15: {"label": "SM_CYMENU", "index": 15, "describle": "Menu bar height"},
                           "SM_CYMENU": {"label": "SM_CYMENU", "index": 15, "describle": "Menu bar height"},
                           16: {"label": "SM_CXFULLSCREEN", "index": 16, "describle": "Full screen client area width"},
                           "SM_CXFULLSCREEN": {"label": "SM_CXFULLSCREEN", "index": 16,
                                               "describle": "Full screen client area width"},
                           17: {"label": "SM_CYFULLSCREEN", "index": 17, "describle": "Full screen client area height"},
                           "SM_CYFULLSCREEN": {"label": "SM_CYFULLSCREEN", "index": 17,
                                               "describle": "Full screen client area height"},
                           18: {"label": "SM_CYKANJIWINDOW", "index": 18, "describle": "Kanji window height"},
                           "SM_CYKANJIWINDOW": {"label": "SM_CYKANJIWINDOW", "index": 18,
                                                "describle": "Kanji window height"},
                           19: {"label": "SM_MOUSEPRESENT", "index": 19, "describle": "Mouse present flag"},
                           "SM_MOUSEPRESENT": {"label": "SM_MOUSEPRESENT", "index": 19,
                                               "describle": "Mouse present flag"},
                           20: {"label": "SM_CYVSCROLL", "index": 20, "describle": "Vertical scroll arrow height"},
                           "SM_CYVSCROLL": {"label": "SM_CYVSCROLL", "index": 20,
                                            "describle": "Vertical scroll arrow height"},
                           21: {"label": "SM_CXHSCROLL", "index": 21, "describle": "Horizontal scroll arrow width"},
                           "SM_CXHSCROLL": {"label": "SM_CXHSCROLL", "index": 21,
                                            "describle": "Horizontal scroll arrow width"},
                           22: {"label": "SM_DEBUG", "index": 22, "describle": "Debug version flag"},
                           "SM_DEBUG": {"label": "SM_DEBUG", "index": 22, "describle": "Debug version flag"},
                           23: {"label": "SM_SWAPBUTTON", "index": 23, "describle": "Mouse buttons swapped flag"},
                           "SM_SWAPBUTTON": {"label": "SM_SWAPBUTTON", "index": 23,
                                             "describle": "Mouse buttons swapped flag"},
                           24: {"label": "SM_CXMIN", "index": 24, "describle": "Minimum window width"},
                           "SM_CXMIN": {"label": "SM_CXMIN", "index": 24, "describle": "Minimum window width"},
                           25: {"label": "SM_CYMIN", "index": 25, "describle": "Minimum window height"},
                           "SM_CYMIN": {"label": "SM_CYMIN", "index": 25, "describle": "Minimum window height"},
                           26: {"label": "SM_CXSIZE", "index": 26, "describle": "Min/Max/Close button width"},
                           "SM_CXSIZE": {"label": "SM_CXSIZE", "index": 26, "describle": "Min/Max/Close button width"},
                           27: {"label": "SM_CYSIZE", "index": 27, "describle": "Min/Max/Close button height"},
                           "SM_CYSIZE": {"label": "SM_CYSIZE", "index": 27, "describle": "Min/Max/Close button height"},
                           28: {"label": "SM_CXSIZEFRAME", "index": 28, "describle": "Window sizing frame width"},
                           "SM_CXSIZEFRAME": {"label": "SM_CXSIZEFRAME", "index": 28,
                                              "describle": "Window sizing frame width"},
                           29: {"label": "SM_CYSIZEFRAME", "index": 29, "describle": "Window sizing frame height"},
                           "SM_CYSIZEFRAME": {"label": "SM_CYSIZEFRAME", "index": 29,
                                              "describle": "Window sizing frame height"},
                           30: {"label": "SM_CXMINTRACK", "index": 30, "describle": "Minimum window tracking width"},
                           "SM_CXMINTRACK": {"label": "SM_CXMINTRACK", "index": 30,
                                             "describle": "Minimum window tracking width"},
                           31: {"label": "SM_CYMINTRACK", "index": 31, "describle": "Minimum window tracking height"},
                           "SM_CYMINTRACK": {"label": "SM_CYMINTRACK", "index": 31,
                                             "describle": "Minimum window tracking height"},
                           32: {"label": "SM_CXDOUBLECLK", "index": 32, "describle": "Double click x tolerance"},
                           "SM_CXDOUBLECLK": {"label": "SM_CXDOUBLECLK", "index": 32,
                                              "describle": "Double click x tolerance"},
                           33: {"label": "SM_CYDOUBLECLK", "index": 33, "describle": "Double click y tolerance"},
                           "SM_CYDOUBLECLK": {"label": "SM_CYDOUBLECLK", "index": 33,
                                              "describle": "Double click y tolerance"},
                           34: {"label": "SM_CXICONSPACING", "index": 34, "describle": "Horizontal icon spacing"},
                           "SM_CXICONSPACING": {"label": "SM_CXICONSPACING", "index": 34,
                                                "describle": "Horizontal icon spacing"},
                           35: {"label": "SM_CYICONSPACING", "index": 35, "describle": "Vertical icon spacing"},
                           "SM_CYICONSPACING": {"label": "SM_CYICONSPACING", "index": 35,
                                                "describle": "Vertical icon spacing"},
                           36: {"label": "SM_MENUDROPALIGNMENT", "index": 36, "describle": "Left or right menu drop"},
                           "SM_MENUDROPALIGNMENT": {"label": "SM_MENUDROPALIGNMENT", "index": 36,
                                                    "describle": "Left or right menu drop"},
                           37: {"label": "SM_PENWINDOWS", "index": 37, "describle": "Pen extensions installed"},
                           "SM_PENWINDOWS": {"label": "SM_PENWINDOWS", "index": 37,
                                             "describle": "Pen extensions installed"},
                           38: {"label": "SM_DBCSENABLED", "index": 38, "describle": "Double-Byte Char Set enabled"},
                           "SM_DBCSENABLED": {"label": "SM_DBCSENABLED", "index": 38,
                                              "describle": "Double-Byte Char Set enabled"},
                           39: {"label": "SM_CMOUSEBUTTONS", "index": 39, "describle": "Number of mouse buttons"},
                           "SM_CMOUSEBUTTONS": {"label": "SM_CMOUSEBUTTONS", "index": 39,
                                                "describle": "Number of mouse buttons"},
                           40: {"label": "SM_SECURE", "index": 40, "describle": "Security present flag"},
                           "SM_SECURE": {"label": "SM_SECURE", "index": 40, "describle": "Security present flag"},
                           41: {"label": "SM_CXEDGE", "index": 41, "describle": "3-D border width"},
                           "SM_CXEDGE": {"label": "SM_CXEDGE", "index": 41, "describle": "3-D border width"},
                           42: {"label": "SM_CYEDGE", "index": 42, "describle": "3-D border height"},
                           "SM_CYEDGE": {"label": "SM_CYEDGE", "index": 42, "describle": "3-D border height"},
                           43: {"label": "SM_CXMINSPACING", "index": 43, "describle": "Minimized window spacing width"},
                           "SM_CXMINSPACING": {"label": "SM_CXMINSPACING", "index": 43,
                                               "describle": "Minimized window spacing width"},
                           44: {"label": "SM_CYMINSPACING", "index": 44,
                                "describle": "Minimized window spacing height"},
                           "SM_CYMINSPACING": {"label": "SM_CYMINSPACING", "index": 44,
                                               "describle": "Minimized window spacing height"},
                           45: {"label": "SM_CXSMICON", "index": 45, "describle": "Small icon width"},
                           "SM_CXSMICON": {"label": "SM_CXSMICON", "index": 45, "describle": "Small icon width"},
                           46: {"label": "SM_CYSMICON", "index": 46, "describle": "Small icon height"},
                           "SM_CYSMICON": {"label": "SM_CYSMICON", "index": 46, "describle": "Small icon height"},
                           47: {"label": "SM_CYSMCAPTION", "index": 47, "describle": "Small caption height"},
                           "SM_CYSMCAPTION": {"label": "SM_CYSMCAPTION", "index": 47,
                                              "describle": "Small caption height"},
                           48: {"label": "SM_CXSMSIZE", "index": 48, "describle": "Small caption button width"},
                           "SM_CXSMSIZE": {"label": "SM_CXSMSIZE", "index": 48,
                                           "describle": "Small caption button width"},
                           49: {"label": "SM_CYSMSIZE", "index": 49, "describle": "Small caption button height"},
                           "SM_CYSMSIZE": {"label": "SM_CYSMSIZE", "index": 49,
                                           "describle": "Small caption button height"},
                           50: {"label": "SM_CXMENUSIZE", "index": 50, "describle": "Menu bar button width"},
                           "SM_CXMENUSIZE": {"label": "SM_CXMENUSIZE", "index": 50,
                                             "describle": "Menu bar button width"},
                           51: {"label": "SM_CYMENUSIZE", "index": 51, "describle": "Menu bar button height"},
                           "SM_CYMENUSIZE": {"label": "SM_CYMENUSIZE", "index": 51,
                                             "describle": "Menu bar button height"},
                           52: {"label": "SM_ARRANGE", "index": 52, "describle": "How minimized windows arranged"},
                           "SM_ARRANGE": {"label": "SM_ARRANGE", "index": 52,
                                          "describle": "How minimized windows arranged"},
                           53: {"label": "SM_CXMINIMIZED", "index": 53, "describle": "Minimized window width"},
                           "SM_CXMINIMIZED": {"label": "SM_CXMINIMIZED", "index": 53,
                                              "describle": "Minimized window width"},
                           54: {"label": "SM_CYMINIMIZED", "index": 54, "describle": "Minimized window height"},
                           "SM_CYMINIMIZED": {"label": "SM_CYMINIMIZED", "index": 54,
                                              "describle": "Minimized window height"},
                           55: {"label": "SM_CXMAXTRACK", "index": 55, "describle": "Maximum draggable width"},
                           "SM_CXMAXTRACK": {"label": "SM_CXMAXTRACK", "index": 55,
                                             "describle": "Maximum draggable width"},
                           56: {"label": "SM_CYMAXTRACK", "index": 56, "describle": "Maximum draggable height"},
                           "SM_CYMAXTRACK": {"label": "SM_CYMAXTRACK", "index": 56,
                                             "describle": "Maximum draggable height"},
                           57: {"label": "SM_CXMAXIMIZED", "index": 57, "describle": "Width of maximized window"},
                           "SM_CXMAXIMIZED": {"label": "SM_CXMAXIMIZED", "index": 57,
                                              "describle": "Width of maximized window"},
                           58: {"label": "SM_CYMAXIMIZED", "index": 58, "describle": "Height of maximized window"},
                           "SM_CYMAXIMIZED": {"label": "SM_CYMAXIMIZED", "index": 58,
                                              "describle": "Height of maximized window"},
                           59: {"label": "SM_NETWORK", "index": 59, "describle": "Network present flag"},
                           "SM_NETWORK": {"label": "SM_NETWORK", "index": 59, "describle": "Network present flag"},
                           60: {"label": "SM_CLEANBOOT", "index": 60, "describle": "How system was booted"},
                           "SM_CLEANBOOT": {"label": "SM_CLEANBOOT", "index": 60, "describle": "How system was booted"},
                           61: {"label": "SM_CXDRAG", "index": 61, "describle": "Avoid drag x tolerance"},
                           "SM_CXDRAG": {"label": "SM_CXDRAG", "index": 61, "describle": "Avoid drag x tolerance"},
                           62: {"label": "SM_CYDRAG", "index": 62, "describle": "Avoid drag y tolerance"},
                           "SM_CYDRAG": {"label": "SM_CYDRAG", "index": 62, "describle": "Avoid drag y tolerance"},
                           63: {"label": "SM_SHOWSOUNDS", "index": 63, "describle": "Present sounds visually"},
                           "SM_SHOWSOUNDS": {"label": "SM_SHOWSOUNDS", "index": 63,
                                             "describle": "Present sounds visually"},
                           64: {"label": "SM_CXMENUCHECK", "index": 64, "describle": "Menu check-mark width"},
                           "SM_CXMENUCHECK": {"label": "SM_CXMENUCHECK", "index": 64,
                                              "describle": "Menu check-mark width"},
                           65: {"label": "SM_CYMENUCHECK", "index": 65, "describle": "Menu check-mark height"},
                           "SM_CYMENUCHECK": {"label": "SM_CYMENUCHECK", "index": 65,
                                              "describle": "Menu check-mark height"},
                           66: {"label": "SM_SLOWMACHINE", "index": 66, "describle": "Slow processor flag"},
                           "SM_SLOWMACHINE": {"label": "SM_SLOWMACHINE", "index": 66,
                                              "describle": "Slow processor flag"},
                           67: {"label": "SM_MIDEASTENABLED", "index": 67,
                                "describle": "Hebrew and Arabic enabled flag"},
                           "SM_MIDEASTENABLED": {"label": "SM_MIDEASTENABLED", "index": 67,
                                                 "describle": "Hebrew and Arabic enabled flag"},
                           68: {"label": "SM_MOUSEWHEELPRESENT", "index": 68, "describle": "Mouse wheel present flag"},
                           "SM_MOUSEWHEELPRESENT": {"label": "SM_MOUSEWHEELPRESENT", "index": 68,
                                                    "describle": "Mouse wheel present flag"},
                           69: {"label": "SM_XVIRTUALSCREEN", "index": 69, "describle": "Virtual screen x origin"},
                           "SM_XVIRTUALSCREEN": {"label": "SM_XVIRTUALSCREEN", "index": 69,
                                                 "describle": "Virtual screen x origin"},
                           70: {"label": "SM_YVIRTUALSCREEN", "index": 70, "describle": "Virtual screen y origin"},
                           "SM_YVIRTUALSCREEN": {"label": "SM_YVIRTUALSCREEN", "index": 70,
                                                 "describle": "Virtual screen y origin"},
                           71: {"label": "SM_CXVIRTUALSCREEN", "index": 71, "describle": "Virtual screen width"},
                           "SM_CXVIRTUALSCREEN": {"label": "SM_CXVIRTUALSCREEN", "index": 71,
                                                  "describle": "Virtual screen width"},
                           72: {"label": "SM_CYVIRTUALSCREEN", "index": 72, "describle": "Virtual screen height"},
                           "SM_CYVIRTUALSCREEN": {"label": "SM_CYVIRTUALSCREEN", "index": 72,
                                                  "describle": "Virtual screen height"},
                           73: {"label": "SM_CMONITORS", "index": 73, "describle": "Number of monitors"},
                           "SM_CMONITORS": {"label": "SM_CMONITORS", "index": 73, "describle": "Number of monitors"},
                           74: {"label": "SM_SAMEDISPLAYFORMAT", "index": 74, "describle": "Same color format flag"},
                           "SM_SAMEDISPLAYFORMAT": {"label": "SM_SAMEDISPLAYFORMAT", "index": 74,
                                                    "describle": "Same color format flag"}

                           }
    def leng(self):
        return len(self.dicByIndex)//2


a=systemMetrics()
print(a.leng())
print(len(a.dicByIndex[73]["label"]))

演示效果截图:

  • 35
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C语言版本的STUN P2P通信代码示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #define STUN_SERVER "stunserver.org" #define STUN_PORT 3478 #define BUF_SIZE 1024 int main() { int sockfd; struct sockaddr_in server_addr; char buffer[BUF_SIZE]; // 创建套接字 if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket creation failed"); exit(EXIT_FAILURE); } // 设置服务器地址 memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(STUN_PORT); if (inet_pton(AF_INET, STUN_SERVER, &(server_addr.sin_addr)) <= 0) { perror("address conversion failed"); exit(EXIT_FAILURE); } // 发送绑定请求 if (sendto(sockfd, "Binding Request", strlen("Binding Request"), 0, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { perror("sending request failed"); exit(EXIT_FAILURE); } // 接收响应 socklen_t addr_len; if (recvfrom(sockfd, buffer, BUF_SIZE, 0, (struct sockaddr*)&server_addr, &addr_len) < 0) { perror("receiving response failed"); exit(EXIT_FAILURE); } // 处理响应数据 printf("STUN response: %s\n", buffer); // 关闭套接字 close(sockfd); return 0; } ``` Python版本的STUN P2P通信代码示例: ```python import socket STUN_SERVER = 'stunserver.org' STUN_PORT = 3478 BUF_SIZE = 1024 def main(): # 创建套接字 sockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 发送绑定请求 sockfd.sendto(b'Binding Request', (STUN_SERVER, STUN_PORT)) # 接收响应 buffer, server_addr = sockfd.recvfrom(BUF_SIZE) # 处理响应数据 print(f"STUN response: {buffer.decode()}") # 关闭套接字 sockfd.close() if __name__ == '__main__': main() ``` 以上是使用C语言Python分别编写的STUN P2P通信示例代码。这些代码向指定的STUN服务器发送绑定请求,并接收响应。请注意,这些示例代码只是简单的演示,实际应用中可能需要更多的功能和错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值