vs2008下C++开发问题汇总

让控制台程序后台运行

【转】C++ 让 Win32 Console Application 程序后台运行

方法一:(无闪现)

添加  
#pragma comment( linker, "/subsystem:"windows" /entry:"mainCRTStartup"" )

方法二:(这个会有闪现)

#include "windows.h"

void main()

{

HWND hwnd;

if(hwnd=::FindWindow("ConsoleWindowClass",NULL)) //找到控制台句柄
{
::ShowWindow(hwnd,SW_HIDE); //隐藏控制台窗口
}

//加入你的代码。程序运行之后,窗口会自动隐藏,只有在任务管理器中的进程中可以看到。

}

      使用以上代码,可以达到隐藏当前控制台窗口的效果。但是,如果系统开机时自动加载此程序,就会发现:控制台窗口没有自动隐藏,如果关闭此窗口,双击此控制台程序,发现窗口隐藏了。要解决此问题,可以使用以下代码:

#include "windows.h"

void main()

{
//开机自动隐藏窗口
HWND hwnd;
hwnd=FindWindow("ConsoleWindowClass",NULL);//找到当前窗口句柄
if(hwnd)
{
   ShowOwnedPopups(hwnd,SW_HIDE);//显示或隐藏由指定窗口所有的全部弹出式窗口
   ShowWindow(hwnd,SW_HIDE);//控制窗口的可见性
   //WinExec 函数: 控制窗口的显示形式
   //假如开机自动运行: C:\WINDOWS\SYSTEM32\KeyboardRec.exe
   WinExec("C:\WINDOWS\SYSTEM32\KeyboardRec.exe",SW_HIDE);
}

//你的其他代码

}

   注意:隐藏窗口的代码,一定要放在主函数的最前面;否则控制台窗口有可能无法隐藏。

方法三:

写一个简单的.vbs文件就可以。实现方法如下:
如,我的.exe文件是HKServer.exe。可以用文本文档写如下代码
[vb]
set wscriptObj = CreateObject("Wscript.Shell")  
wscriptObj.run "C:UsersHKDesktopHKServerEditVersion2.4DebugHKServer.exe",0 
保存成.vbs文件,直接运行.vbs文件即可实现.exe文件后台运行。

方法四:创建服务

写个批处理 如:
@echo off
sc create  my_Service binPath= "F:Browser.exe"
sc start   my_Service

但是主程序必须按服务的方式写,一般的main入口的不行。

Windows中查找命令的路径 (类似Linux中的which命令)

  1. where is a direct equivalent:

    C:UsersJoey>where cmd
    C:WindowsSystem32cmd.exe

    Note that in PowerShell where itself is an alias for Where-Object, thus you need to usewhere.exe in PowerShell.

  2. In cmd you can also use for:

    C:UsersJoey>for %x in (powershell.exe) do @echo %~$PATH:x
    C:WindowsSystem32WindowsPowerShellv1.0powershell.exe
  3. In PowerShell you have Get-Command and its alias gcm which does the same if you pass an argument (but also works for aliases, cmdlets and functions in PowerShell):

    PS C:UsersJoey> Get-Command where
    
    CommandType     Name          Definition
    -----------     ----          ----------
    Alias           where         Where-Object
    Application     where.exe     C:Windowssystem32where.exe

    The first returned command is the one that would be executed.

获取应用程序路径

一、

1.只获得路径字串不包含文件名

TCHAR szFilePath[MAX_PATH + 1]={0};
GetModuleFileName(NULL, szFilePath, MAX_PATH);
(_tcsrchr(szFilePath, _T('\')))[1] = 0; // 删除文件名,只获得路径字串
CString str_url = szFilePath;  // 例如str_url==e:programDebug
---------------------------------------------------------
2.获得双斜杠路径不包含文件名

TCHAR _szPath[MAX_PATH + 1]={0};
GetModuleFileName(NULL, _szPath, MAX_PATH);
(_tcsrchr(_szPath, _T('\')))[1] = 0;//删除文件名,只获得路径 字串
CString strPath;
for (int n=0;_szPath[n];n++)
{
if (_szPath[n]!=_T('\'))
{
strPath +=_szPath[n] ;
}
else
{
strPath += _T("\\");
}
}

MessageBox(strPath);//输出==e:\program\Debug\


二、
1:获取应用程序自身完整路径文件名
方法1:
#include "stdlib.h"
void main()
{
cout << _pgmptr << endl;
}

方法2:
char szFullPath[MAX_PATH];
ZeroMemory(szFullPath,MAX_PAT);
::GetModuleFileName(NULL,szFullPath,MAX_PATH);
::MessageBox(NULL,szFullPath,"path",MB_ICONINFORMATION);

方法3:
TCHAR szPath[MAX_PATH] = {0};
if(!GetModuleFileName(NULL, szPath, MAX_PATH))
{ return ; }
AfxMessageBox(szPath);

2:如何获取应用程序所在目录?
这里值得注意的是很多人都用
GetCurrentDirectory(MAX_PATH, szCurrentPath);
来获取。这个方法并不好,经常出错,比如现在我有一个程序在d: est目录下,现在运行这个程序后用GetCurrentDirectory得到的是d: est

。接着在程序里用CFileDialog来打开一个C: est est.txt文件后再调用GetCurrentDirectory,那么得到的szCurrentPath就是C: est而不是d: est。

推荐用如下方法来得到当前程序所在目录比较安全:
void _splitpath( const char *path, char *drive, char *dir, char *fname, char *ext );
函数来分解开始提到的_pgmptr,然后再用
void _makepath( char *path, const char *drive, const char *dir, const char *fname, const char *ext );
函数来对分解后的路径进行组合。这两个函数结合起来功能强大,使用灵活,基本上所有的有关目录和路径方面的操作都可以搞定。

转载于:http://hi.baidu.com/wyuanshiy/blog/item/7818a5ec6ffab422269791dc.html

 程序单实例运行

http://blog.csdn.net/earbao/article/details/8672661

获得进程id

http://www.cnblogs.com/dabaopku/archive/2010/07/06/1772407.html

Windows中关闭进程的C++实现

http://blog.csdn.net/thinkhy/article/details/5044761

查看端口被哪个进程占用

一、在windows命令行窗口下执行:运行--cmd
C:>netstat -aon|findstr "8080" 
TCP     127.0.0.1:80       0.0.0.0:0             LISTENING    2448
端口被进程号为2448的进程占用,继续执行下面命令:
C:>tasklist|findstr "2448" 
thread.exe                   2016 Console                 0     16,064 K

很清楚,thread占用了你的端口,Kill it

命令:taskkill -F -PID 2448

如果第二步查不到,那就开任务管理器,进程---查看---选择列---pid(进程位标识符)打个勾就可以了
看哪个进程是2448,然后杀之即可。

在安装WAMP时,也经常遇到这种问题,说是80端口被占,就把前面的8080改成80即可

二、在Liuux下执行命令:netstat -tlnp |grep **

socket编程实例

#include <stdio.h>
#include <string.h>
#include <winsock2.h>

#pragma comment(lib, "ws2_32.lib")

int main()
{
    WORD sockVer = MAKEWORD(2, 2);
    WSADATA wsaData;
    if (WSAStartup(sockVer, &wsaData) != 0)
        return 0;
    SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (slisten == INVALID_SOCKET) {
        printf("socket error!
");
        return 0;
    }
    int ret = 0;
    sockaddr_in sin;
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(0);
    //sin.sin_addr.S_un.S_addr = INADDR_ANY;
    sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    ret = bind(slisten, (LPSOCKADDR)&sin, sizeof(sin));
    if (ret == INVALID_SOCKET) {
        printf("bind error!
");
        return 0;
    }
    ret = listen(slisten, 5);
    if (ret == INVALID_SOCKET) {
        printf("listen error!
");
        return 0;
    }
    /*
    sockaddr_in local;
    int len = sizeof(local);
    getsockname(slisten, (LPSOCKADDR)&local, &len);
    int port = ntohs(local.sin_port);
    */
    SOCKET sClient;
    sockaddr_in remoteAddr;
    int nAddrlen = sizeof(remoteAddr);
    char recvData[255];
    while (1) {
        sClient = accept(slisten, (SOCKADDR*)&remoteAddr, &nAddrlen);
        if (sClient == INVALID_SOCKET) {
            printf("accept error!
");
            continue;
        }
        ret = recv(sClient, recvData, 255, 0);
        if (ret > 0) {
            recvData[ret] = 0;
            printf(recvData);
        }
        char *sendData = "hello, tcp client!
";
        send(sClient, sendData, strlen(sendData), 0);
        closesocket(sClient);
    }
    closesocket(slisten);
    WSACleanup();

    return 0;
}
View Code

 c语言编写windows服务程序

http://blog.csdn.net/fww330666557/article/details/8845930

http://blog.csdn.net/pi9nc/article/details/8176367

bat判断服务是否存在

@echo off
REM 将引号内部分改成你要查找的服务名称
sc query |find /i "server" >nul 2>nul
REM 如果服务存在,跳转至exist标签
if not errorlevel 1 (goto exist) else goto notexist

:exist
REM 这里写服务存在时用的代码
goto :eof

:notexist
REM 这里写服务不存在时用的代码
goto :eof

====================================================================

例子:    服务名:mysql

@echo off

REM 将引号内部分改成你要查找的服务名称

sc query |find /i "mysql" >nul 2>nul

REM 如果服务存在,跳转至exist标签
if not errorlevel 1 (goto exist) else goto notexist

:exist

REM 服务存在时启用mysql服务
net start mysql
goto :eof

:notexist

REM 服务不存在时安装mysql服务
cd bin
mysqld.exe --install mysql
net start mysql
goto :eof

windows下多线程实例

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

HANDLE stopEvent = NULL;

DWORD WINAPI thread_func(LPVOID para)
{
    for (int i = 0; i < 10; i++)
    {
        printf("hello,%d
", i);
        if (i == 6)
            SetEvent(stopEvent);
        Sleep(1000);
    }
    return 0;
}

DWORD WINAPI thread_exit(LPVOID para)
{
    WaitForSingleObject(stopEvent, INFINITE);
    exit(0);
    return NULL;
}

int main()
{
    stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    CreateThread(NULL,0,thread_exit,NULL,0,NULL);
    HANDLE h = CreateThread(NULL,0,thread_func,NULL,0,NULL);
    WaitForSingleObject(h, INFINITE);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/feilv/p/5576706.html