C语言操作剪切板内容!win32程序

来源:互联网 发布:sql语句增加一列数据 编辑:程序博客网 时间:2024/05/29 08:11
#include <windows.h>#include <iostream>#include <sys/types.h>#include <sys/stat.h>#include <shellapi.h>using namespace std;//显示消息void show(string str);//获取剪切板内容string getPlateStr();//根据文件路径获取所在文件夹的路径string getFileDir(string path);//判断是否为文件bool isFile(string path);//判断是否为文件夹bool isDir(string path);//运行程序或路径void execute(string s);//宽字符串转普通字符串char *wtoc(wchar_t *wText);//普通字符串转宽字符串wchar_t *ctow(char *sText);int WINAPI WinMain(    HINSTANCE hInstance,       //程序当前实例的句柄,以后随时可以用GetModuleHandle(0)来获得    HINSTANCE hPrevInstance,   //这个参数在Win32环境下总是0,已经废弃不用了    char * lpCmdLine,          //指向以/0结尾的命令行,不包括EXE本身的文件名,                               //以后随时可以用GetCommandLine()来获取完整的命令行    int nCmdShow               //指明应该以什么方式显示主窗口){string plateStr = getPlateStr();show(plateStr);if(isDir(plateStr)){execute(plateStr);}if(isFile(plateStr)){execute(getFileDir(plateStr));}return 0;}//显示消息void show(string str){MessageBox(NULL, str.c_str(), "", MB_OK);}//判断是否为文件夹bool isDir(string path){struct _stat buf = {0};    _stat(path.c_str(), &buf);    return buf.st_mode & _S_IFDIR;}//判断是否为文件bool isFile(string path){struct _stat buf = {0};    _stat(path.c_str(), &buf);    return buf.st_mode & _S_IFREG;}//根据文件路径获取所在文件夹的路径string getFileDir(string path){int i = path.find_last_of('\\');std::string p2 = path.substr(0, i);MessageBox(NULL, (const char *)p2.c_str(), "", MB_OK);return p2.c_str();}//获取剪切板内容string getPlateStr(){OpenClipboard(NULL);HGLOBAL hGlobal = NULL;hGlobal = ::GetClipboardData(CF_UNICODETEXT);wchar_t *pGlobal = (wchar_t *)::GlobalLock(hGlobal);CloseClipboard();return wtoc(pGlobal);}//运行程序或路径void execute(std::string s){ShellExecute(    NULL,    ("open"),    ("Explorer.exe"),    (s.c_str()),    NULL,SW_SHOWDEFAULT);}//宽字符串转普通字符串char *wtoc(wchar_t *wText){DWORD dwNum = WideCharToMultiByte(CP_ACP, NULL, wText, -1,NULL, 0, NULL, FALSE);char *psText = NULL;psText = new char[dwNum];if(!psText){delete []psText;psText = NULL;}WideCharToMultiByte (CP_ACP, NULL, wText, -1,psText, dwNum, NULL, FALSE);return psText;}//普通字符串转宽字符串wchar_t *ctow(char *sText){DWORD dwNum = MultiByteToWideChar (CP_ACP,  0, sText, -1, NULL, 0); wchar_t *pwText = NULL;pwText = new wchar_t[dwNum];if(!pwText){delete []pwText;pwText = NULL;}unsigned nLen = MultiByteToWideChar (CP_ACP, 0, sText, -1, pwText, dwNum+10);if (nLen >= 0){pwText[nLen] = 0;}return pwText;}