﻿<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>学习日记 &#187; win32</title>
	<atom:link href="https://www.softwareace.cn/?cat=20&#038;feed=rss2" rel="self" type="application/rss+xml" />
	<link>https://www.softwareace.cn</link>
	<description>时刻想着为自己的产品多做一些对他好的事情</description>
	<lastBuildDate>Fri, 20 Mar 2026 06:58:28 +0000</lastBuildDate>
	<language>zh-CN</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	
	<item>
		<title>ws2def.h(206) : error C2011: “sockaddr”: “struct”类型重定义</title>
		<link>https://www.softwareace.cn/?p=1700</link>
		<comments>https://www.softwareace.cn/?p=1700#comments</comments>
		<pubDate>Fri, 13 Oct 2017 07:40:11 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.softwareace.cn/?p=1700</guid>
		<description><![CDATA[参考来源： http://www.cnblogs.com/tonyyang132/archive/2009/1 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p><span style="color: #3d3d3d;"><b>参考来源：</b></p>
<p>http://www.cnblogs.com/tonyyang132/archive/2009/10/14/1583110.html</p>
<p>https://social.msdn.microsoft.com/Forums/vstudio/en-US/671124df-c42b-48b8-a4ac-3413230bc43b/dll-compilationredefinition-error?forum=vclanguage</span><b style="color: #3d3d3d;"><br />
现象：</b><br style="color: #3d3d3d;" /><span style="color: #3d3d3d;">使用winsock2后，出现许多重定义错误。</span><br style="color: #3d3d3d;" /><b style="color: #3d3d3d;">原因是:</b><br style="color: #3d3d3d;" /><span style="color: #3d3d3d;">头文件包含顺序错误，这两个头文件是：#include &lt;winsock2.h&gt;和#include&lt;windows.h&gt;</span><br style="color: #3d3d3d;" /><b style="color: #3d3d3d;">解决办法：</b><br style="color: #3d3d3d;" /><span style="color: #3d3d3d;">在使用的地方加上如下语句：</span><br style="color: #3d3d3d;" /><span style="color: #3d3d3d;">//socket</span><br style="color: #3d3d3d;" /><span style="color: #3d3d3d;">#ifndef WIN32_LEAN_AND_MEAN</span><br style="color: #3d3d3d;" /><span style="color: #3d3d3d;">#define WIN32_LEAN_AND_MEAN</span><br style="color: #3d3d3d;" /><span style="color: #3d3d3d;">#endif</span><br style="color: #3d3d3d;" /><br style="color: #3d3d3d;" /><span style="color: #3d3d3d;">#include &lt;windows.h&gt;</span><br style="color: #3d3d3d;" /><span style="color: #3d3d3d;">#include &lt;winsock2.h&gt;</span></p>
<p>http://blog.163.com/lys_19850716/blog/static/84129044201611653736905/</p>
]]></content:encoded>
			<wfw:commentRss>https://www.softwareace.cn/?feed=rss2&#038;p=1700</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>发一个自己写的安卓绿色安装器</title>
		<link>https://www.softwareace.cn/?p=1619</link>
		<comments>https://www.softwareace.cn/?p=1619#comments</comments>
		<pubDate>Fri, 31 Mar 2017 02:44:58 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.softwareace.cn/?p=1619</guid>
		<description><![CDATA[有空写了一个安装器，网上的要么很大，要么TMD还一堆广告。坑爹！ 用自己的绿色版本吧，无任何广告，多爽！ 上截 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p style="color: #454545;">有空写了一个安装器，网上的要么很大，要么TMD还一堆广告。坑爹！<br />
用自己的绿色版本吧，无任何广告，多爽！<br />
上截图<br />
<a style="color: red;" href="http://static.ithtw.com/wp-content/uploads/2015/03/2015032319404512.jpg" data-lightbox="image_lg"><img class="alignnone size-full wp-image-1529" src="http://static.ithtw.com/wp-content/uploads/2015/03/2015032319404512.jpg" alt="QQ截图20150323193828" width="614" height="291" data-bd-imgshare-binded="1" /></a></p>
<p style="color: #454545;">核心源码:</p>
<p></p><pre class="crayon-plain-tag">// ApkInstallerDlg.cpp : 实现文件
//
 
#include "stdafx.h"
#include "ApkInstaller.h"
#include "ApkInstallerDlg.h"
#include "afxdialogex.h"
 
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
 
// CApkInstallerDlg 对话框
static void Tokenize(CString text, CString split, CStringArray &amp;list)
{
    CString partStr;
    int position = 0;
    do
    {
        partStr = text.Tokenize(split, position);
        if (partStr != T(""))
        {
            int offset = partStr.Find(T("device"));
            list.Add(partStr.Mid(0,offset).Trim());
        }
    } while (!partStr.IsEmpty());
}
 
static void GT_UTF8ToGBK(CString &amp;strUTF8)  
{  
    //获取转换为多字节后需要的缓冲区大小，创建多字节缓冲区
    UINT nLen = MultiByteToWideChar(CP_UTF8,NULL,strUTF8,-1,NULL,NULL);
    WCHAR *wszBuffer = new WCHAR[nLen+1];
    nLen = MultiByteToWideChar(CP_UTF8,NULL,strUTF8,-1,wszBuffer,nLen);
    wszBuffer[nLen] = 0;
 
    nLen = WideCharToMultiByte(CP_ACP,NULL,wszBuffer,-1,NULL,NULL,NULL,NULL);
    CHAR *szBuffer = new CHAR[nLen+1];
    nLen = WideCharToMultiByte(CP_ACP,NULL,wszBuffer,-1,szBuffer,nLen,NULL,NULL);
    szBuffer[nLen] = 0;  
 
    strUTF8 = szBuffer;
    //清理内存
    delete []szBuffer;
    delete []wszBuffer;
}
 
static CString ParseName(CString strProp,CString beginLabel,CString endLabel)
{
    int mPos = strProp.Find(beginLabel);
    if (mPos != -1)
    {
        mPos += beginLabel.GetLength();
        int mEnd = strProp.Find(endLabel,mPos);
        if(mEnd != -1)
        {
            return strProp.Mid(mPos,mEnd-mPos);
        }
    }
    return "";
}
 
//函数名称：AssociateApkFile
//函数功能：关联apk文件和图标
//输入参数：strType 文件类型  .apk .mpk等
//     strPath 程序路径名 与文件关联的可执行程序的带路径的文件名
//返 回 值：NULL
//函数说明：
static void AssociateFile(CString strType, CString strPath) {
    //HKEY_LOCAL_MACHINE/Software/Classes/等于HKEY_CLASSES_ROOT
    HKEY hkey;
    CString strKeyName("ITHTW");
    CString strResult("");
    LPBYTE OwnerGet = new BYTE[80]; //定义用户姓名
    memset(OwnerGet, 0, 80);
    DWORD dType1 = REG_SZ; //定义数据类型
    DWORD dLength = 80; //定义数据长度
    CString strValue("");
    CString strRegPath("");
    strRegPath = strType + "\\"; // .apk
    // 设置路径"HKEY_CLASS_ROOT\\.apk"的键值，关联.apk文件用
    if (RegOpenKey(HKEY_CLASSES_ROOT, strRegPath, &amp;hkey) == ERROR_SUCCESS) {
        RegQueryValueEx(hkey, NULL, NULL, &amp;dType1, OwnerGet, &amp;dLength);
        strResult = (LPTSTR) OwnerGet;
        if (-1 == strResult.Find(CString("ITHTW"))) {
            strValue.Format("ITHTW");
            RegSetValue(hkey, _T(""), REG_SZ, strValue,
                strValue.GetLength() + 1);
            RegSetValueEx(hkey, "", 0, REG_SZ,
                (const BYTE*) strValue.GetBuffer(strValue.GetLength()),
                strValue.GetLength() + 1);
            RegCloseKey(hkey);
        }
    } else {
        if (RegCreateKey(HKEY_CLASSES_ROOT, strType, &amp;hkey) != ERROR_SUCCESS) {
            return;
        } else {
            strValue.Format("ITHTW");
            RegSetValue(hkey, _T(""), REG_SZ, strValue,
                strValue.GetLength() + 1);
            RegSetValueEx(hkey, "", 0, REG_SZ,
                (const BYTE*) strValue.GetBuffer(strValue.GetLength()),
                strValue.GetLength() + 1);
            RegCloseKey(hkey);
        }
    }
    // 设置"SOFTWARE\\Classes\\.apk"的键值
    memset(OwnerGet, 0, 80);
    if (strResult.IsEmpty())
        strResult.Empty();
    strValue.Empty();
    strRegPath = CString("SOFTWARE\\Classes\\") + strType + "\\"; // SOFTWARE\\Classes\\.apk
    if ( RegOpenKey( HKEY_LOCAL_MACHINE, strRegPath, &amp;hkey ) == ERROR_SUCCESS )
    {
        RegQueryValueEx(hkey, NULL, NULL, &amp;dType1, OwnerGet, &amp;dLength);
        strResult = (LPTSTR) OwnerGet;
        if (-1 == strResult.Find("ITHTW")) {
            // 该关键字下没有我的软件相关名,修改之
            strValue.Format("ITHTW");
            RegSetValue(hkey, _T(""), REG_SZ, strValue,
                strValue.GetLength() + 1);
            RegSetValueEx(hkey, "", 0, REG_SZ,
                (const BYTE*) strValue.GetBuffer(strValue.GetLength()),
                strValue.GetLength() + 1);
            RegCloseKey(hkey);
        }
    }
    else
    {
        if ( RegCreateKey( HKEY_LOCAL_MACHINE, strRegPath, &amp;hkey ) != ERROR_SUCCESS )
        {
            return;
        }
        else
        {
            strValue.Format("ITHTW");
            RegSetValue(hkey, _T(""), REG_SZ, strValue, strValue.GetLength()+1);
            RegSetValueEx(hkey, "", 0, REG_SZ, (const BYTE*)strValue.GetBuffer(strValue.GetLength()), strValue.GetLength()+1);
            RegCloseKey(hkey);
        }
    }
    // 设置路径"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.apk\\UserChoice"的值
    memset(OwnerGet, 0, 80);
    if (strResult.IsEmpty())
        strResult.Empty();
    strValue.Empty();
    strRegPath =
        CString(
        "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\")
        + strType + "\\UserChoice";
    if (RegOpenKey(HKEY_CURRENT_USER, strRegPath, &amp;hkey) == ERROR_SUCCESS) {
        RegQueryValueEx(hkey, NULL, NULL, &amp;dType1, OwnerGet, &amp;dLength);
        strResult = (LPTSTR) OwnerGet;
        if (-1 == strResult.Find("ITHTW")) {
            // 该关键字下没有我的软件相关名,修改之
            strValue.Format("ITHTW");
            RegSetValue(hkey, "Progid", REG_SZ, strValue,
                strValue.GetLength() + 1);
            RegSetValueEx(hkey, "Progid", 0, REG_SZ,
                (const BYTE*) strValue.GetBuffer(strValue.GetLength()),
                strValue.GetLength() + 1);
            RegCloseKey(hkey);
        }
    } else {
        if (RegCreateKey(HKEY_CURRENT_USER, strRegPath, &amp;hkey)
            != ERROR_SUCCESS) {
                return;
        } else {
            strValue.Format("ITHTW");
            RegSetValue(hkey, "Progid", REG_SZ, strValue,
                strValue.GetLength() + 1);
            RegSetValueEx(hkey, "Progid", 0, REG_SZ,
                (const BYTE*) strValue.GetBuffer(strValue.GetLength()),
                strValue.GetLength() + 1);
            RegCloseKey(hkey);
        }
    }
    memset(OwnerGet, 0, 80);
    if (strResult.IsEmpty())
        strResult.Empty();
    strValue.Empty();
    strRegPath =
        CString(
        "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\")
        + strType;
    if (RegOpenKey(HKEY_CURRENT_USER, strRegPath, &amp;hkey) == ERROR_SUCCESS) {
        RegQueryValueEx(hkey, NULL, NULL, &amp;dType1, OwnerGet, &amp;dLength);
        strResult = (LPTSTR) OwnerGet;
        if (-1 == strResult.Find("ITHTW")) {
            // 该关键字下没有我的软件相关名,修改之
            strValue.Format("ITHTW");
            RegSetValue(hkey, "Progid", REG_SZ, strValue,
                strValue.GetLength() + 1);
            RegSetValueEx(hkey, "Progid", 0, REG_SZ,
                (const BYTE*) strValue.GetBuffer(strValue.GetLength()),
                strValue.GetLength() + 1);
            RegCloseKey(hkey);
        }
    } else {
        if (RegCreateKey(HKEY_CURRENT_USER, strRegPath, &amp;hkey)
            != ERROR_SUCCESS) {
                return;
        } else {
            strValue.Format("ITHTW");
            RegSetValue(hkey, "Progid", REG_SZ, strValue,
                strValue.GetLength() + 1);
            RegSetValueEx(hkey, "Progid", 0, REG_SZ,
                (const BYTE*) strValue.GetBuffer(strValue.GetLength()),
                strValue.GetLength() + 1);
            RegCloseKey(hkey);
        }
    }
    // 通知系统，文件关联改变了
    SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
    SHChangeNotify(SHCNE_UPDATEIMAGE, SHCNF_DWORD, NULL, NULL);
}
 
CApkInstallerDlg::CApkInstallerDlg(CWnd* pParent /*=NULL*/)
    : CDialogEx(CApkInstallerDlg::IDD, pParent)
{
    m_hIcon = AfxGetApp()-&gt;LoadIcon(IDR_MAINFRAME);
    memset(szCommand,0,sizeof(szCommand));
    memset(szPath,0,sizeof(szPath));
    hEvent = CreateEvent(NULL,FALSE,TRUE,NULL);
}
 
void CApkInstallerDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
}
 
BEGIN_MESSAGE_MAP(CApkInstallerDlg, CDialogEx)
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    ON_WM_DROPFILES()
    ON_BN_CLICKED(IDC_BTN_INSTALL, &amp;CApkInstallerDlg::OnBnClickedBtnInstall)
    ON_BN_CLICKED(IDC_BTN_UNINSTALL, &amp;CApkInstallerDlg::OnBnClickedBtnUninstall)
    ON_BN_CLICKED(IDC_BTN_REG, &amp;CApkInstallerDlg::OnBnClickedBtnReg)
END_MESSAGE_MAP()
 
 
// CApkInstallerDlg 消息处理程序
 
CString ReadDeviceName(CString cmd)
{
    CApkInstallerDlg* dlg = (CApkInstallerDlg*)AfxGetApp()-&gt;GetMainWnd();
    char buffer[10240] = {0};
    DWORD dwRead = 0;
    HANDLE hReadPipe = NULL;
    dlg-&gt;ProcessTask(&amp;hReadPipe,cmd.GetBuffer());
    cmd.ReleaseBuffer();
    CString text;
    while (ReadFile(hReadPipe,buffer,10240,&amp;dwRead,0))
    {
        CString temp(buffer,dwRead);
        temp = temp.Trim();
        text += temp;
    }
    return text;
}
 
void CApkInstallerDlg::ReadDevices(void)
{
    _tcscpy_s(szCommand,T("adb devices"));
    //开始读取
    char buffer[10240] = {0};
    DWORD dwRead = 0;
    HANDLE hReadPipe = NULL;
    ProcessTask(&amp;hReadPipe,szCommand);
    CString text;
    while (ReadFile(hReadPipe,buffer,10240,&amp;dwRead,0))
    {
        CString temp(buffer,dwRead);
        temp = temp.Trim();
        text += temp;
    }
    Tokenize(text,T("\n"),devices);
    CComboBox *comboBox = (CComboBox*)GetDlgItem(IDC_COMBO_DEVICES);
    for (int i=1;i&lt;devices.GetCount();i++)//过滤第一list信息
    {
        CString prop = ReadDeviceName("adb -s "+devices.GetAt(i)+" shell getprop");
        CString manufacturer = ParseName(prop,"&amp;#91;ro.product.manufacturer&amp;#93;: &amp;#91;","&amp;#93;");
        CString mode = ParseName(prop,"&amp;#91;ro.product.model&amp;#93;: &amp;#91;","&amp;#93;");
        comboBox-&gt;AddString(manufacturer+mode);
    }
    if(comboBox-&gt;GetCount() &gt; 0)
        comboBox-&gt;SetCurSel(0);
}
 
BOOL CApkInstallerDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();
 
    // 设置此对话框的图标。当应用程序主窗口不是对话框时，框架将自动
    //  执行此操作
    SetIcon(m_hIcon, TRUE);            // 设置大图标
    SetIcon(m_hIcon, FALSE);        // 设置小图标
 
    // TODO: 在此添加额外的初始化代码
 
    ReadDevices();
    SetDlgItemText(IDC_EDIT_LOG,T("日志"));
    if(_tcslen(szPath) == 0)
        SetDlgItemText(IDC_EDIT_FILE,T("文件路径"));
    else
    {
        SetDlgItemText(IDC_EDIT_FILE,szPath);
        if (CheckApk(szPath))
        {
            //获取包名
            SetSzCommand(T("aapt d badging "),CMD_GET_READ_INFO);
            _tcscat_s(szCommand,szPath);
            AfxBeginThread(ReadThread,this);
        }
    }
    return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}
 
// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。
 
void CApkInstallerDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // 用于绘制的设备上下文
 
        SendMessage(WM_ICONERASEBKGND, reinterpret_cast&lt;WPARAM&gt;(dc.GetSafeHdc()), 0);
 
        // 使图标在工作区矩形中居中
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&amp;rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;
 
        // 绘制图标
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialogEx::OnPaint();
        CRect rt;
        GetDlgItem(IDC_STATIC_ICO)-&gt;GetWindowRect(&amp;rt);
        CPoint p(rt.left,rt.top);
        ::ScreenToClient(m_hWnd,&amp;p);
 
        CDC *pDC = GetDC();
        Graphics graphics(pDC-&gt;m_hDC);
        Image *img = NULL;
        ImageFromID(IDB_PNG_ANDROID,img);
        graphics.DrawImage(img,p.x-20,p.y);
        FontFamily fontFamily(L"微软雅黑");
        Gdiplus::Font font(&amp;fontFamily, 11, FontStyleRegular, UnitPoint);
        PointF pointF((REAL)(p.x+10), (REAL)p.y+30);
        SolidBrush solidBrush(Color(255, 0, 0, 0)); 
        //TCHAR string[MAX_PATH] = T("安装器");
        WCHAR string[MAX_PATH] = L"安装器";
        graphics.DrawString(string, (INT)wcslen(string), &amp;font, pointF,&amp;solidBrush);
        if(img != NULL)
            delete img;
        ReleaseDC(pDC);
    }
}
 
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CApkInstallerDlg::OnQueryDragIcon()
{
    return static_cast&lt;HCURSOR&gt;(m_hIcon);
}
 
 
void CApkInstallerDlg::OnDropFiles(HDROP hDropInfo)
{
    // TODO: 在此添加消息处理程序代码和/或调用默认值
    TCHAR file_name[MAX_PATH] = {0};
    ::DragQueryFile(hDropInfo,0, file_name, MAX_PATH);
    SetDlgItemText(IDC_EDIT_FILE,file_name);
    if (CheckApk(file_name))
    {
        //获取包名
        SetSzCommand(T("aapt d badging "),CMD_GET_READ_INFO);
        _tcscat_s(szCommand,file_name);
        AfxBeginThread(ReadThread,this);
    }
    CDialogEx::OnDropFiles(hDropInfo);
}
 
 
UINT CApkInstallerDlg::ReadThread(LPVOID pVoid)
{
    try{
        CApkInstallerDlg *dlg = (CApkInstallerDlg*)pVoid;
        WaitForSingleObject(dlg-&gt;hEvent,INFINITE);
        dlg-&gt;SetWindowText(T("处理中,请稍后..."));
         
        //开始读取
        char buffer[10240] = {0};
        DWORD dwRead = 0;
        HANDLE hReadPipe = NULL;
        dlg-&gt;ProcessTask(&amp;hReadPipe,dlg-&gt;szCommand);
        CString text;
        while (ReadFile(hReadPipe,buffer,10240,&amp;dwRead,0))
        {
            CString temp(buffer,dwRead);
            GT_UTF8ToGBK(temp);
            text += temp;
        }
        text.Trim();
        if (text.GetLength() &gt; 0)
        {
             if (dlg-&gt;nCommand == CMD_INSTALL_APP)
            {
                dlg-&gt;SetDlgItemText(IDC_EDIT_LOG,text);
            }
            else if (dlg-&gt;nCommand == CMD_GET_READ_INFO)
            {
                dlg-&gt;SetDlgItemText(IDC_EDIT_LOG,text);
                CString temp = T("package: name='");
                int startIndex = text.Find(temp);
                int endIndex = text.Find(T("'"),startIndex+temp.GetLength());
                int nCount = endIndex - startIndex - temp.GetLength();
                if(startIndex &gt;= 0 &amp;&amp; nCount &gt; 0)
                    dlg-&gt;packAge=text.Mid(startIndex+temp.GetLength(),nCount);
            }
            else if (dlg-&gt;nCommand == CMD_UNINSTALL)
            {
                if(hReadPipe != NULL)
                    CloseHandle(hReadPipe);
                hReadPipe = NULL;
                dlg-&gt;ProcessTask(&amp;hReadPipe,dlg-&gt;szCommand);
                if (ReadFile(hReadPipe,buffer,10240,&amp;dwRead,0))
                {
                    CString new_text(buffer,dwRead);
                    new_text = new_text.Trim();
                    dlg-&gt;SetDlgItemText(IDC_EDIT_LOG,new_text);
                }
            }
        }
        else
        {
            //控制台数据读取失败
            strcpy_s(buffer,"数据读取失败");
        }
        CloseHandle(hReadPipe);
        dlg-&gt;SetWindowText(T("处理完成"));
        SetEvent(dlg-&gt;hEvent);
    }catch(CException *e)
    {
        TCHAR msg[512];
        e-&gt;GetErrorMessage(msg,512);
        AfxMessageBox(msg);
    }
    return 0;
}
 
 
UINT CApkInstallerDlg::ProcessTask(HANDLE* hReadPipe,TCHAR* strCommand)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    si.cb = sizeof(STARTUPINFO);
    GetStartupInfo(&amp;si);
 
 
    SECURITY_ATTRIBUTES sa = {0};
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;
 
    HANDLE hWritePipe = NULL;
    if(!CreatePipe(hReadPipe,&amp;hWritePipe,&amp;sa,0))
    {
        AfxMessageBox(T("创建管道失败"));
        return 0;
    }
 
    si.hStdOutput = hWritePipe;
    si.hStdError = hWritePipe;
    si.wShowWindow = SW_HIDE;
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    if (CreateProcess (NULL,strCommand,NULL,NULL,TRUE,NULL,NULL,NULL,&amp;si,&amp;pi))
    {
        //等待进程执行完毕
        //WaitForSingleObject(pi.hProcess,INFINITE);
        //关闭进程和主线程句柄
        CloseHandle (pi.hProcess);
        CloseHandle (pi.hThread);
    }
    //关闭写入句柄
    CloseHandle(hWritePipe);
    return 0;
}
 
void CApkInstallerDlg::SetSzCommand(TCHAR* wstr,CMD_TYPE nType)
{
    memset(szCommand,0,sizeof(szCommand));
    _tcscpy_s(szCommand,wstr);
    this-&gt;nCommand = nType;
}
 
 
void CApkInstallerDlg::OnBnClickedBtnUninstall()
{
    // TODO: 在此添加控件通知处理程序代码
    try
    {
        TCHAR file_name[512] = {0};
        GetDlgItemText(IDC_EDIT_FILE,file_name,512);
        if (CheckApk(file_name))
        {
            SetDlgItemText(IDC_EDIT_LOG,T("正在卸载:")+packAge);
            //卸载
            SetSzCommand(T("adb -s "),CMD_UNINSTALL);
            CComboBox *comboBox = (CComboBox*)GetDlgItem(IDC_COMBO_DEVICES);
            int cur = comboBox-&gt;GetCurSel();
            if (cur &gt;= 0 &amp;&amp; cur &lt; devices.GetCount()-1)
            {
                CString device = devices.GetAt(cur+1);
                _tcscat_s(szCommand,device);
                _tcscat_s(szCommand,T(" uninstall "));
                _tcscat_s(szCommand,packAge);
                AfxBeginThread(ReadThread,this);
            }
        }
    }
    catch (CException* e)
    {
        TCHAR msg&amp;#91;512&amp;#93;;
        e-&gt;GetErrorMessage(msg,512);
        MessageBox(msg);
    }
}
 
void CApkInstallerDlg::OnBnClickedBtnInstall()
{
    // TODO: 在此添加控件通知处理程序代码
    try
    {
        TCHAR file_name[512] = {0};
        GetDlgItemText(IDC_EDIT_FILE,file_name,512);
        if (CheckApk(file_name))
        {
            SetDlgItemText(IDC_EDIT_LOG,T("正在安装:")+CString(file_name));
            SetSzCommand(T("adb -s "),CMD_INSTALL_APP);
            CComboBox *comboBox = (CComboBox*)GetDlgItem(IDC_COMBO_DEVICES);
            int cur = comboBox-&gt;GetCurSel();
            if (cur &gt;= 0 &amp;&amp; cur &lt; devices.GetCount()-1)
            {
                CString device = devices.GetAt(cur+1);
                _tcscat_s(szCommand,device);
                _tcscat_s(szCommand,T(" install "));
                _tcscat_s(szCommand,file_name);
                AfxBeginThread(ReadThread,this);
            }
        }
    }
    catch (CException* e)
    {
        TCHAR msg&amp;#91;512&amp;#93;;
        e-&gt;GetErrorMessage(msg,512);
        MessageBox(msg);
    }
}
 
 
BOOL CApkInstallerDlg::CheckApk(TCHAR* path)
{
    try
    {
        TCHAR* exist = _tcsstr(path,T("apk"));
        if (exist == NULL)
        {
            MessageBox(T(""));
            return FALSE;
        }
        CFileFind finder;
        if(!finder.FindFile(path))
        {
            MessageBox(T("指定文件不存在"));
            return FALSE;
        }
    }
    catch (CException* e)
    {
        TCHAR msg[512];
        e-&gt;GetErrorMessage(msg,512);
        MessageBox(msg);
    }
    return TRUE;
}
 
void CApkInstallerDlg::OnBnClickedBtnReg()
{
    // TODO: 在此添加控件通知处理程序代码
    TCHAR szName[512];
    GetModuleFileName(NULL,szName,sizeof(szName)*sizeof(TCHAR));
    AssociateFile(".apk",szName);
}</pre><p>&nbsp;</p>
<p style="color: #454545;">项目源码下载:<a style="color: #2a7ab3;" href="http://static.ithtw.com/wp-content/uploads/2015/03/2015032319414968.7z">ApkInstaller</a><br />
编译好的APP:<a style="color: #2a7ab3;" href="http://static.ithtw.com/wp-content/uploads/2015/03/2015032319422564.7z">Release</a></p>
<p style="color: #454545;">本文固定链接: <a style="color: #518ab2;" title="发一个自己写的安卓绿色安装器" href="http://www.ithtw.com/1528.html" rel="bookmark">http://www.ithtw.com/1528.html</a></p>
]]></content:encoded>
			<wfw:commentRss>https://www.softwareace.cn/?feed=rss2&#038;p=1619</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++读取文件PE头</title>
		<link>https://www.softwareace.cn/?p=1613</link>
		<comments>https://www.softwareace.cn/?p=1613#comments</comments>
		<pubDate>Fri, 31 Mar 2017 02:36:48 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.softwareace.cn/?p=1613</guid>
		<description><![CDATA[[crayon-69dec817d236e375847032/] &#160;]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">#include "stdafx.h"
#include &lt;windows.h&gt;
#include &lt;stdio.h&gt;
#include &lt;iostream&gt;
 
#ifndef _X_PE_H_
#define _X_PE_H_
//获取PE头基地址
#define SIZE_OF_NT_SIGNATURE sizeof(DWORD)
#define NTSIGNATURE(a) ((LPVOID)((BYTE *)a + ((PIMAGE_DOS_HEADER)a)-&gt;e_lfanew - 1))
#define PEFHDROFFSET(a) ((LPVOID)((BYTE *)a + ((PIMAGE_DOS_HEADER)a)-&gt;e_lfanew - 1 + SIZE_OF_NT_SIGNATURE))
#define OPTHDROFFSET(a) ((LPVOID)((BYTE *)a + ((PIMAGE_DOS_HEADER)a)-&gt;e_lfanew - 1 + SIZE_OF_NT_SIGNATURE + sizeof(IMAGE_FILE_HEADER)))
DWORD WINAPI ImageFileType (LPVOID lpFile);
#endif
 
using namespace std;
//PE文件类型判断
DWORD WINAPI ImageFileType (LPVOID lpFile)
{
    /* 首先出现的是DOS文件标志 */
    if (*(USHORT *)lpFile == IMAGE_DOS_SIGNATURE)
    {
        /* 由DOS头部决定PE文件头部的位置 */
        if (LOWORD (*(DWORD *)NTSIGNATURE (lpFile)) ==
            IMAGE_OS2_SIGNATURE ||
            LOWORD (*(DWORD *)NTSIGNATURE (lpFile)) ==
            IMAGE_OS2_SIGNATURE_LE)
            return (DWORD)LOWORD(*(DWORD *)NTSIGNATURE (lpFile));
        else if (*(DWORD *)NTSIGNATURE (lpFile) ==
            IMAGE_NT_SIGNATURE)
            return IMAGE_NT_SIGNATURE;
        else
            return IMAGE_DOS_SIGNATURE;
    }
    else
        /* 不明文件种类 */
        return 0;
}
int main()
{
    //业务信息参考
    //http://www.vckbase.com/document/viewdoc/?id=1334
 
    CHAR szBuf[2048];
    FILE* pFile;
    fopen_s(&amp;pFile,"F:\\SVN\\Debug\\LGT.exe","r");//这里加载一个PE文件
    int iRead=fread(szBuf,1,2048,pFile);
 
    //MZ-DOS头
    IMAGE_DOS_HEADER* dos;
    dos=(IMAGE_DOS_HEADER*)szBuf;
    cout.setf(ios::hex,ios::basefield);//设置十六进制显示数值
    cout.setf(ios::showbase|ios::uppercase);//设置0x头和大写
    cout&lt;&lt;"dos-&gt;e_magic="&lt;&lt;dos-&gt;e_magic&lt;&lt;endl;
    cout&lt;&lt;"dos-&gt;e_lfanew="&lt;&lt;dos-&gt;e_lfanew&lt;&lt;endl;
    cout&lt;&lt;"NTSIGNATURE="&lt;&lt;*(DWORD *)NTSIGNATURE(szBuf)&lt;&lt;endl;
    cout&lt;&lt;"ImageFileType="&lt;&lt;ImageFileType(szBuf)&lt;&lt;" is ";
    switch(ImageFileType(szBuf))
    {
    case IMAGE_DOS_SIGNATURE://MZ
        cout&lt;&lt;"IMAGE_DOS_SIGNATURE"&lt;&lt;endl;
        break;
    case IMAGE_OS2_SIGNATURE://NE
        cout&lt;&lt;"IMAGE_OS2_SIGNATURE"&lt;&lt;endl;
        break;
    case IMAGE_OS2_SIGNATURE_LE:
        cout&lt;&lt;"IMAGE_OS2_SIGNATURE_LE"&lt;&lt;endl;
        break;
    case IMAGE_NT_SIGNATURE:
        cout&lt;&lt;"IMAGE_NT_SIGNATURE"&lt;&lt;endl;
    }
 
    cout&lt;&lt;"PEFHDROFFSET="&lt;&lt;PEFHDROFFSET(szBuf)&lt;&lt;endl;
    //PE必选头
    PIMAGE_FILE_HEADER header =(PIMAGE_FILE_HEADER)PEFHDROFFSET(szBuf);
    cout&lt;&lt;"Machine="&lt;&lt;header-&gt;Machine&lt;&lt;endl;
    cout&lt;&lt;"区段数NumberOfSections="&lt;&lt;header-&gt;NumberOfSections&lt;&lt;endl;
    cout&lt;&lt;"建立时间TimeDateStamp="&lt;&lt;header-&gt;TimeDateStamp&lt;&lt;endl;
    cout&lt;&lt;"PointerToSymbolTable="&lt;&lt;header-&gt;PointerToSymbolTable&lt;&lt;endl;
    cout&lt;&lt;"可选头部大小SizeOfOptionalHeader="&lt;&lt;header-&gt;SizeOfOptionalHeader&lt;&lt;endl;
    cout&lt;&lt;"特征Characteristics="&lt;&lt;header-&gt;Characteristics&lt;&lt;endl;
 
    //PE可选头
    PIMAGE_OPTIONAL_HEADER opHeader=(PIMAGE_OPTIONAL_HEADER)OPTHDROFFSET(szBuf);
    cout&lt;&lt;"魔术字Magic="&lt;&lt;opHeader-&gt;Magic&lt;&lt;endl;//0x010B为.EXE，0x0107为ROM映像
    cout&lt;&lt;"连接器主版本MajorLinkerVersion="&lt;&lt;(short)opHeader-&gt;MajorLinkerVersion&lt;&lt;endl;
    cout&lt;&lt;"连接器副版本MinorLinkerVersion="&lt;&lt;(short)opHeader-&gt;MinorLinkerVersion&lt;&lt;endl;
    cout&lt;&lt;"可执行代码大小SizeOfCode="&lt;&lt;opHeader-&gt;SizeOfCode&lt;&lt;endl;
    cout&lt;&lt;"已初始化的数据大小SizeOfInitializedData="&lt;&lt;opHeader-&gt;SizeOfInitializedData&lt;&lt;endl;
    cout&lt;&lt;"未初始化的数据大小SizeOfUninitializedData="&lt;&lt;opHeader-&gt;SizeOfUninitializedData&lt;&lt;endl;
    cout&lt;&lt;"入口点AddressOfEntryPoint="&lt;&lt;opHeader-&gt;AddressOfEntryPoint&lt;&lt;endl;
    cout&lt;&lt;"代码基址(.text段)BaseOfCode="&lt;&lt;opHeader-&gt;BaseOfCode&lt;&lt;endl;
    cout&lt;&lt;"数据基址(.bss段)BaseOfData="&lt;&lt;opHeader-&gt;BaseOfData&lt;&lt;endl;
    cout&lt;&lt;"映像基址ImageBase"&lt;&lt;opHeader-&gt;ImageBase&lt;&lt;endl;//进程映像地址空间中的首选基地址,Windows NT的Microsoft Win32 SDK链接器将这个值默认设为0x00400000，但是你可以使用-BASE:linker开关改变这个值。 
    cout&lt;&lt;"区段对齐SectionAlignment="&lt;&lt;opHeader-&gt;SectionAlignment&lt;&lt;endl;
    cout&lt;&lt;"FileAlignment="&lt;&lt;opHeader-&gt;FileAlignment&lt;&lt;endl;
    cout&lt;&lt;"NT主版本号MajorOperatingSystemVersion="&lt;&lt;opHeader-&gt;MajorOperatingSystemVersion&lt;&lt;endl;
    cout&lt;&lt;"NT副版本号MinorOperatingSystemVersion="&lt;&lt;opHeader-&gt;MinorOperatingSystemVersion&lt;&lt;endl;
    cout&lt;&lt;"应用程序主版本号MajorImageVersion="&lt;&lt;opHeader-&gt;MajorImageVersion&lt;&lt;endl;
    cout&lt;&lt;"应用程序副版本号MinorImageVersion="&lt;&lt;opHeader-&gt;MinorImageVersion&lt;&lt;endl;
    cout&lt;&lt;"Win32子系统主版本号MajorSubsystemVersion="&lt;&lt;opHeader-&gt;MajorSubsystemVersion&lt;&lt;endl;
    cout&lt;&lt;"Win32子系统副版本号MinorSubsystemVersion="&lt;&lt;opHeader-&gt;MinorSubsystemVersion&lt;&lt;endl;
    cout&lt;&lt;"SizeOfImage="&lt;&lt;opHeader-&gt;SizeOfImage&lt;&lt;endl;
    cout&lt;&lt;"头大小SizeOfHeaders="&lt;&lt;opHeader-&gt;SizeOfHeaders&lt;&lt;endl;
    cout&lt;&lt;"校验和CheckSum="&lt;&lt;opHeader-&gt;CheckSum&lt;&lt;endl;//私有算法
    cout&lt;&lt;"子系统Subsystem="&lt;&lt;opHeader-&gt;Subsystem&lt;&lt;endl;
    cout&lt;&lt;"DllCharacteristics="&lt;&lt;opHeader-&gt;DllCharacteristics&lt;&lt;endl;
    cout&lt;&lt;"SizeOfStackReserve="&lt;&lt;opHeader-&gt;SizeOfStackReserve&lt;&lt;endl;
    cout&lt;&lt;"SizeOfStackCommit="&lt;&lt;opHeader-&gt;SizeOfStackCommit&lt;&lt;endl;
    cout&lt;&lt;"SizeOfHeapReserve="&lt;&lt;opHeader-&gt;SizeOfHeapReserve&lt;&lt;endl;
    cout&lt;&lt;"SizeOfHeapCommit="&lt;&lt;opHeader-&gt;SizeOfHeapCommit&lt;&lt;endl;
    cout&lt;&lt;"LoaderFlags="&lt;&lt;opHeader-&gt;LoaderFlags&lt;&lt;endl;
    cout&lt;&lt;"NumberOfRvaAndSizes="&lt;&lt;opHeader-&gt;NumberOfRvaAndSizes&lt;&lt;endl;
    cout&lt;&lt;"导出表RVA:"&lt;&lt;opHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress&lt;&lt;endl;
    cout&lt;&lt;"导出表大小:"&lt;&lt;opHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size&lt;&lt;endl;
    cout&lt;&lt;"导入表RVA:"&lt;&lt;opHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress&lt;&lt;endl;
    cout&lt;&lt;"导入表大小:"&lt;&lt;opHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size&lt;&lt;endl;
    cout&lt;&lt;"资源RVA:"&lt;&lt;opHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress&lt;&lt;endl;
    cout&lt;&lt;"资源大小:"&lt;&lt;opHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size&lt;&lt;endl;
    cout&lt;&lt;"TLSRVA:"&lt;&lt;opHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress&lt;&lt;endl;
    cout&lt;&lt;"TLS大小:"&lt;&lt;opHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size&lt;&lt;endl;
    cout&lt;&lt;"调试RVA:"&lt;&lt;opHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress&lt;&lt;endl;
    cout&lt;&lt;"调试:"&lt;&lt;opHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size&lt;&lt;endl;
 
    cout&lt;&lt;sizeof(IMAGE_OPTIONAL_HEADER)&lt;&lt;endl;
    PIMAGE_SECTION_HEADER ps=(PIMAGE_SECTION_HEADER)((BYTE*)opHeader+sizeof(IMAGE_OPTIONAL_HEADER));
 
    //打印所有的段信息
    for (int i=0;i&lt;header-&gt;NumberOfSections;i++)
    {
        cout&lt;&lt;endl;
        cout&lt;&lt;"Name="&lt;&lt;ps[i].Name&lt;&lt;endl;
        cout&lt;&lt;"PhysicalAddress="&lt;&lt;ps[i].Misc.PhysicalAddress&lt;&lt;endl;
        cout&lt;&lt;"VirtualSize="&lt;&lt;ps[i].Misc.VirtualSize&lt;&lt;endl;
        cout&lt;&lt;"VirtualAddress="&lt;&lt;ps[i].VirtualAddress&lt;&lt;endl;
        cout&lt;&lt;"SizeOfRawData="&lt;&lt;ps[i].SizeOfRawData&lt;&lt;endl;
        cout&lt;&lt;"PointerToRawData="&lt;&lt;ps[i].PointerToRawData&lt;&lt;endl;
        cout&lt;&lt;"PointerToRelocations="&lt;&lt;ps[i].PointerToRelocations&lt;&lt;endl;
        cout&lt;&lt;"PointerToLinenumbers="&lt;&lt;ps[i].PointerToLinenumbers&lt;&lt;endl;
        cout&lt;&lt;"NumberOfRelocations="&lt;&lt;ps[i].NumberOfRelocations&lt;&lt;endl;
        cout&lt;&lt;"NumberOfLinenumbers="&lt;&lt;ps[i].NumberOfLinenumbers&lt;&lt;endl;
        cout&lt;&lt;"Characteristics="&lt;&lt;ps[i].Characteristics&lt;&lt;endl;
    }
    system("pause");
    return 0;
}</pre><p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://www.softwareace.cn/?feed=rss2&#038;p=1613</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++ 获取父进程</title>
		<link>https://www.softwareace.cn/?p=1583</link>
		<comments>https://www.softwareace.cn/?p=1583#comments</comments>
		<pubDate>Thu, 16 Feb 2017 06:33:04 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.softwareace.cn/?p=1583</guid>
		<description><![CDATA[[crayon-69dec817d2609787109159/] &#160;]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">// Win32Project2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include &lt;iostream&gt;
#include &lt;wtypes.h&gt;
#include&lt;tlhelp32.h&gt;
#include &lt;psapi.h&gt;
#pragma   comment(lib,"psapi.lib")
using namespace std;
#define ProcessBasicInformation 0 

typedef struct
{
    DWORD ExitStatus;
    DWORD PebBaseAddress;
    DWORD AffinityMask;
    DWORD BasePriority;
    ULONG UniqueProcessId;
    ULONG InheritedFromUniqueProcessId;
}   PROCESS_BASIC_INFORMATION;

typedef LONG(__stdcall *PROCNTQSIP)(HANDLE, UINT, PVOID, ULONG, PULONG);
//
DWORD GetParentProcessID(DWORD dwProcessId);

int _tmain(int argc, _TCHAR* argv[])
{
    //  输入文件名
    HANDLE   hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32   procentry;//=sizeof(PROCESSENTRY32); 
    BOOL   bFlag = Process32First(hSnapShot, &amp;procentry);
    DWORD       parentprocessid;
    while (bFlag)
    {
        if (_stricmp(procentry.szExeFile, "QQExternal.exe") == 0) //你的程序
        {
            DWORD       processid = procentry.th32ProcessID;         //找到 
            cout &lt;&lt; procentry.th32ProcessID &lt;&lt; endl;
            cout &lt;&lt; GetParentProcessID(procentry.th32ProcessID) &lt;&lt; endl;
            parentprocessid = GetParentProcessID(procentry.th32ProcessID);
        }
        bFlag = Process32Next(hSnapShot, &amp;procentry);
    }
    cout &lt;&lt; parentprocessid &lt;&lt; endl;


    HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, parentprocessid);
    char processName[MAX_PATH] = { 0 };
    GetModuleBaseName(processHandle, 0, processName, MAX_PATH);
    char  processFullPath[MAX_PATH] = { 0 };
    GetModuleFileNameEx(processHandle, 0, processFullPath, MAX_PATH);


    cout &lt;&lt; processName &lt;&lt; endl;
    cout &lt;&lt; processFullPath &lt;&lt; endl;
    //cout &lt;&lt; Environment::CommandLine&lt;&lt; endl;
    system("pause");
    return 0;
}

DWORD GetParentProcessID(DWORD dwProcessId)
{
    LONG                        status;
    DWORD                        dwParentPID = (DWORD)-1;
    HANDLE                        hProcess;
    PROCESS_BASIC_INFORMATION    pbi;

    PROCNTQSIP NtQueryInformationProcess = (PROCNTQSIP)GetProcAddress(
        GetModuleHandle("ntdll"), "NtQueryInformationProcess");

    if (NULL == NtQueryInformationProcess)
    {
        return (DWORD)-1;
    }
    // Get process handle
    hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcessId);
    if (!hProcess)
    {
        return (DWORD)-1;
    }

    // Retrieve information
    status = NtQueryInformationProcess(hProcess,
        ProcessBasicInformation,
        (PVOID)&amp;pbi,
        sizeof(PROCESS_BASIC_INFORMATION),
        NULL
        );

    // Copy parent Id on success
    if (!status)
    {
        dwParentPID = pbi.InheritedFromUniqueProcessId;
    }

    CloseHandle(hProcess);

    return dwParentPID;

}</pre><p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://www.softwareace.cn/?feed=rss2&#038;p=1583</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>获取运行过程中改名的文件的路径</title>
		<link>https://www.softwareace.cn/?p=1580</link>
		<comments>https://www.softwareace.cn/?p=1580#comments</comments>
		<pubDate>Thu, 12 Jan 2017 03:01:26 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.softwareace.cn/?p=1580</guid>
		<description><![CDATA[需求 一个 EXE 在运行过程中（被）改名了，需要准确地获取它的文件名。 尝试 原本以为这是一个非常简单的 C [&#8230;]]]></description>
				<content:encoded><![CDATA[<h3 id="section" class="clickable-header top-level-header">需求</h3>
<p>一个 EXE 在运行过程中（被）改名了，需要准确地获取它的文件名。</p>
<h3 id="section-1" class="clickable-header top-level-header">尝试</h3>
<p>原本以为这是一个非常简单的 CASE，直接用 GetModuleFileName 不就行了吗？结果还真不如我所想。无论程序运行过程中被改名成什么样子，GetModuleFileName 返回的都是 EXE 开始运行时的名字。然后又尝试了 GetProcessImageFileName，也是如此，直到最后找到了 QueryFullProcessImageName。</p>
<h3 id="section-2" class="clickable-header top-level-header">示例代码</h3>
<p></p><pre class="crayon-plain-tag">#include &lt;Windows.h&gt;
#include &lt;Psapi.h&gt;
#include &lt;stdio.h&gt;

#pragma comment(lib, "Psapi.lib")

void OutputSelfpath()
{
	char szFile[MAX_PATH] = {0};
	GetModuleFileName(NULL, szFile, MAX_PATH);
	printf("GetModuleFileName:\n\r%s\n\n", szFile);

	memset(szFile, 0, MAX_PATH);

	HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
	if (!hProcess)
	{
		printf("OpenProcess failed!\n");
	}
	else
	{
		DWORD dwRet = GetProcessImageFileName(hProcess, szFile, MAX_PATH);
		if (dwRet)
		{
			printf("GetProcessImageFileName:\n\r%s\n\n", szFile);
		}
		else
		{
			printf("GetProcessImageFileName failed!\n");
		}

        memset(szFile, 0, MAX_PATH);
		DWORD dwSize = MAX_PATH;
		if (QueryFullProcessImageName(hProcess, 0, szFile, &amp;dwSize))
		{
			printf("QueryFullProcessImageName:\n\r%s\n\n", szFile);
		}
		else
		{
			printf("QueryFullProcessImageName failed\n", szFile);
		}
	}
}

int main()
{
	const char* pszFile = "ConsoleTest.exe";
	const char* pszNewFile = "ConsoleTest_bak.exe";
	remove(pszNewFile);

	OutputSelfpath();

	int nRet = rename(pszFile, pszNewFile);

	if (0 != nRet)
	{
		printf("rename file failed!\n");
	}
	else
	{
		printf("################### after rename ###################\n\n");
		OutputSelfpath();
	}

	system("pause");
	return 0;
}</pre><p>&nbsp;</p>
<h3 id="section-3" class="clickable-header top-level-header">运行结果</h3>
<p><img src="http://mazhuang.org/images/posts/windows/queryfullprocessimagename.png" alt="QueryFullProcessImageName" /></p>
<h3 id="section-4" class="clickable-header top-level-header">思考</h3>
<p>现象上讲就是如此了，这几个 API 的本质区别是什么呢？待续。</p>
<p>http://mazhuang.org/2014/10/09/path-after-rename/</p>
]]></content:encoded>
			<wfw:commentRss>https://www.softwareace.cn/?feed=rss2&#038;p=1580</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>宏与参数，类型冲突 pop_macro</title>
		<link>https://www.softwareace.cn/?p=1575</link>
		<comments>https://www.softwareace.cn/?p=1575#comments</comments>
		<pubDate>Thu, 22 Dec 2016 09:06:54 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.softwareace.cn/?p=1575</guid>
		<description><![CDATA[[crayon-69dec817d29fd495254384/] &#160;]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">//a.h
#include "b.h"
class A{
#pragma push_macro("aaaa")
#undef aaaa
  void fuckyou( int aaaa);
#pragma pop_macro("aaaa")
};

//b.h

#define aaaa (*__daylight())</pre><p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://www.softwareace.cn/?feed=rss2&#038;p=1575</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>解决Duilib创建的win32窗口拖到屏幕上边缘自动最大化</title>
		<link>https://www.softwareace.cn/?p=1561</link>
		<comments>https://www.softwareace.cn/?p=1561#comments</comments>
		<pubDate>Fri, 16 Dec 2016 09:55:19 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.softwareace.cn/?p=1561</guid>
		<description><![CDATA[转载:http://bbs.csdn.net/topics/390842294 使用Duilib创建窗口的时候 [&#8230;]]]></description>
				<content:encoded><![CDATA[<div id="cnblogs_post_body" style="color: #666666;">
<p>转载:<a style="color: #f03331;" href="http://bbs.csdn.net/topics/390842294" target="_blank">http://bbs.csdn.net/topics/390842294</a></p>
<p>使用Duilib创建窗口的时候，假如有这样一个需求：</p>
<p>1.窗口大小规定</p>
<p>2.不可拖拽改变窗口大小</p>
<p>3.双击标题栏禁止最大化</p>
<p>4.禁止拖拽窗口到屏幕上边沿最大化</p>
<p><img src="http://images2015.cnblogs.com/blog/552373/201609/552373-20160927141948703-1546827683.gif" alt="" /></p>
<p>针对以上四点,给出解决办法:</p>
<p>1.设置size=&#8221;宽,高&#8221;</p>
<p>2.sizebox=&#8221;0,0,0,0&#8243;</p>
<p>3.在HandleMessage中屏蔽掉WM_NCLBUTTONDBLCLK</p>
<p>&nbsp;</p><pre class="crayon-plain-tag">case WM_NCLBUTTONDBLCLK:
  //不做处理
{
    return 0;
}
break;</pre><p>&nbsp;</p>
<p>4.要修改窗口风格</p>
<p>&nbsp;</p><pre class="crayon-plain-tag">//修改窗口风格
    SetWindowLong(m_hWnd,GWL_STYLE,GetWindowLong(m_hWnd,GWL_STYLE) &amp; ~WS_MAXIMIZEBOX &amp; ~WS_THICKFRAME );</pre><p>&nbsp;</p>
<p>设置完成后:</p>
<p><img src="http://images2015.cnblogs.com/blog/552373/201609/552373-20160927143733110-1065364614.gif" alt="" /></p>
<p>&nbsp;</p>
</div>
<div class="clear" style="color: #666666;"></div>
<div id="blog_post_info_block" style="color: #666666;"></div>
]]></content:encoded>
			<wfw:commentRss>https://www.softwareace.cn/?feed=rss2&#038;p=1561</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>unistd.h  windows</title>
		<link>https://www.softwareace.cn/?p=1472</link>
		<comments>https://www.softwareace.cn/?p=1472#comments</comments>
		<pubDate>Thu, 28 Jul 2016 04:34:23 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.softwareace.cn/?p=1472</guid>
		<description><![CDATA[[crayon-69dec817d2db8219026314/] &#160;]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">//unistd.h 
#ifndef _UNISTD_H
#define _UNISTD_H 
#include &lt;io.h&gt; 
#include &lt;process.h&gt; 
#endif /* _UNISTD_H */</pre><p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://www.softwareace.cn/?feed=rss2&#038;p=1472</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>memmem windows</title>
		<link>https://www.softwareace.cn/?p=1469</link>
		<comments>https://www.softwareace.cn/?p=1469#comments</comments>
		<pubDate>Wed, 27 Jul 2016 08:16:11 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.softwareace.cn/?p=1469</guid>
		<description><![CDATA[[crayon-69dec817d2f82264092137/] &#160;]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">#include &lt;string.h&gt;

/*
 * Find the first occurrence of the byte string s in byte string l.
 */

const void *
memmem(const void *l, size_t l_len, const void *s, size_t s_len)
{
	register char *cur, *last;
	const char *cl = (const char *)l;
	const char *cs = (const char *)s;

	/* we need something to compare */
	if (l_len == 0 || s_len == 0)
		return NULL;

	/* "s" must be smaller or equal to "l" */
	if (l_len &lt; s_len)
		return NULL;

	/* special case where s_len == 1 */
	if (s_len == 1)
		return memchr(l, (int)*cs, l_len);

	/* the last position where its possible to find "s" in "l" */
	last = (char *)cl + l_len - s_len;

	for (cur = (char *)cl; cur &lt;= last; cur++)
		if (cur[0] == cs[0] &amp;&amp; memcmp(cur, cs, s_len) == 0)
			return cur;

	return NULL;
}</pre><p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://www.softwareace.cn/?feed=rss2&#038;p=1469</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>mman.h  windows</title>
		<link>https://www.softwareace.cn/?p=1466</link>
		<comments>https://www.softwareace.cn/?p=1466#comments</comments>
		<pubDate>Wed, 27 Jul 2016 08:04:52 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.softwareace.cn/?p=1466</guid>
		<description><![CDATA[[crayon-69dec817d31a0584490175/] &#160; [crayon-69dec81 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p></p><pre class="crayon-plain-tag">//mman.h
/*
 * sys/mman.h
 * mman-win32
 */

#ifndef _SYS_MMAN_H_
#define _SYS_MMAN_H_

#ifndef _WIN32_WINNT		// Allow use of features specific to Windows XP or later.                   
#define _WIN32_WINNT 0x0501	// Change this to the appropriate value to target other versions of Windows.
#endif						

/* All the headers include this file. */
#ifndef _MSC_VER
#include &lt;_mingw.h&gt;
#endif

#include &lt;sys/types.h&gt;

#ifdef __cplusplus
extern "C" {
#endif

#define PROT_NONE       0
#define PROT_READ       1
#define PROT_WRITE      2
#define PROT_EXEC       4

#define MAP_FILE        0
#define MAP_SHARED      1
#define MAP_PRIVATE     2
#define MAP_TYPE        0xf
#define MAP_FIXED       0x10
#define MAP_ANONYMOUS   0x20
#define MAP_ANON        MAP_ANONYMOUS

#define MAP_FAILED      ((void *)-1)

/* Flags for msync. */
#define MS_ASYNC        1
#define MS_SYNC         2
#define MS_INVALIDATE   4

void*   mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off);
int     munmap(void *addr, size_t len);
int     mprotect(void *addr, size_t len, int prot);
int     msync(void *addr, size_t len, int flags);
int     mlock(const void *addr, size_t len);
int     munlock(const void *addr, size_t len);

#ifdef __cplusplus
};
#endif

#endif /*  _SYS_MMAN_H_ */</pre><p>&nbsp;</p><pre class="crayon-plain-tag">//mman.c

#include &lt;windows.h&gt;
#include &lt;errno.h&gt;
#include &lt;io.h&gt;

#include "mman.h"

#ifndef FILE_MAP_EXECUTE
#define FILE_MAP_EXECUTE    0x0020
#endif /* FILE_MAP_EXECUTE */

static int __map_mman_error(const DWORD err, const int deferr)
{
    if (err == 0)
        return 0;
    //TODO: implement
    return err;
}

static DWORD __map_mmap_prot_page(const int prot)
{
    DWORD protect = 0;
    
    if (prot == PROT_NONE)
        return protect;
        
    if ((prot &amp; PROT_EXEC) != 0)
    {
        protect = ((prot &amp; PROT_WRITE) != 0) ? 
                    PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ;
    }
    else
    {
        protect = ((prot &amp; PROT_WRITE) != 0) ?
                    PAGE_READWRITE : PAGE_READONLY;
    }
    
    return protect;
}

static DWORD __map_mmap_prot_file(const int prot)
{
    DWORD desiredAccess = 0;
    
    if (prot == PROT_NONE)
        return desiredAccess;
        
    if ((prot &amp; PROT_READ) != 0)
        desiredAccess |= FILE_MAP_READ;
    if ((prot &amp; PROT_WRITE) != 0)
        desiredAccess |= FILE_MAP_WRITE;
    if ((prot &amp; PROT_EXEC) != 0)
        desiredAccess |= FILE_MAP_EXECUTE;
    
    return desiredAccess;
}

void* mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off)
{
    HANDLE fm, h;
    
    void * map = MAP_FAILED;
    
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4293)
#endif

    const DWORD dwFileOffsetLow = (sizeof(off_t) &lt;= sizeof(DWORD)) ? 
                    (DWORD)off : (DWORD)(off &amp; 0xFFFFFFFFL);
    const DWORD dwFileOffsetHigh = (sizeof(off_t) &lt;= sizeof(DWORD)) ?
                    (DWORD)0 : (DWORD)((off &gt;&gt; 32) &amp; 0xFFFFFFFFL);
    const DWORD protect = __map_mmap_prot_page(prot);
    const DWORD desiredAccess = __map_mmap_prot_file(prot);

    const off_t maxSize = off + (off_t)len;

    const DWORD dwMaxSizeLow = (sizeof(off_t) &lt;= sizeof(DWORD)) ? 
                    (DWORD)maxSize : (DWORD)(maxSize &amp; 0xFFFFFFFFL);
    const DWORD dwMaxSizeHigh = (sizeof(off_t) &lt;= sizeof(DWORD)) ?
                    (DWORD)0 : (DWORD)((maxSize &gt;&gt; 32) &amp; 0xFFFFFFFFL);

#ifdef _MSC_VER
#pragma warning(pop)
#endif

    errno = 0;
    
    if (len == 0 
        /* Unsupported flag combinations */
        || (flags &amp; MAP_FIXED) != 0
        /* Usupported protection combinations */
        || prot == PROT_EXEC)
    {
        errno = EINVAL;
        return MAP_FAILED;
    }
    
    h = ((flags &amp; MAP_ANONYMOUS) == 0) ? 
                    (HANDLE)_get_osfhandle(fildes) : INVALID_HANDLE_VALUE;

    if ((flags &amp; MAP_ANONYMOUS) == 0 &amp;&amp; h == INVALID_HANDLE_VALUE)
    {
        errno = EBADF;
        return MAP_FAILED;
    }

    fm = CreateFileMapping(h, NULL, protect, dwMaxSizeHigh, dwMaxSizeLow, NULL);

    if (fm == NULL)
    {
        errno = __map_mman_error(GetLastError(), EPERM);
        return MAP_FAILED;
    }
  
    map = MapViewOfFile(fm, desiredAccess, dwFileOffsetHigh, dwFileOffsetLow, len);

    CloseHandle(fm);
  
    if (map == NULL)
    {
        errno = __map_mman_error(GetLastError(), EPERM);
        return MAP_FAILED;
    }

    return map;
}

int munmap(void *addr, size_t len)
{
    if (UnmapViewOfFile(addr))
        return 0;
        
    errno =  __map_mman_error(GetLastError(), EPERM);
    
    return -1;
}

int mprotect(void *addr, size_t len, int prot)
{
    DWORD newProtect = __map_mmap_prot_page(prot);
    DWORD oldProtect = 0;
    
    if (VirtualProtect(addr, len, newProtect, &amp;oldProtect))
        return 0;
    
    errno =  __map_mman_error(GetLastError(), EPERM);
    
    return -1;
}

int msync(void *addr, size_t len, int flags)
{
    if (FlushViewOfFile(addr, len))
        return 0;
    
    errno =  __map_mman_error(GetLastError(), EPERM);
    
    return -1;
}

int mlock(const void *addr, size_t len)
{
    if (VirtualLock((LPVOID)addr, len))
        return 0;
        
    errno =  __map_mman_error(GetLastError(), EPERM);
    
    return -1;
}

int munlock(const void *addr, size_t len)
{
    if (VirtualUnlock((LPVOID)addr, len))
        return 0;
        
    errno =  __map_mman_error(GetLastError(), EPERM);
    
    return -1;
}</pre><p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://www.softwareace.cn/?feed=rss2&#038;p=1466</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
