begin process at 2012 05 27 16:18:08
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Tutoriaux

 > UNE FENÊTRE QUI SE SAUVE QUAND ON PASSE DESSUS, STOPPE CTRL-ALT-SUP

UNE FENÊTRE QUI SE SAUVE QUAND ON PASSE DESSUS, STOPPE CTRL-ALT-SUP


 Information sur la source

Note :
Aucune note
Catégorie :Tutoriaux Niveau :Débutant Date de création :26/01/2004 Vu / téléchargé :4 543 / 246

Auteur : largoce

Ecrire un message privé
Site perso
Commentaire sur cette source (2)
Ajouter un commentaire et/ou une note

 Description

Bonjour à tous,
Bon voilà c'est mon premier petit programme en C++ (je viens du PHP et c'est pas pareil, lol).
Bon d'accord il ne fait rien en soit, mais il permet de voir pour les novices (comme moi) comment :
- Ouvrir une fenêtre
- Inter-agir avec les évènements: souris-clavier
- Fermer une fenêtre quand il y a un survol de souris, et exécuter un programme.
- Exécuter un programme quand on clique sur Alt-F4
- Comment agir avec le Focus et légèrement détourner Ctrl-Alt-Sup

Bon voilà, un peu d'indulgence serait sympa.
J'ai fait ça parce que c'est plus facile d'apprendre en faisant des "petites conneries" que de s'atteler directement à des programmes lourds. J'espère pouvoir faire des prog intéressant un jour quand même... ;-)

Enfin un gros merci à Brunews et à la communauté qui m'ont indirectement aidé grâce à la lecture des nombreux messages du forum.

Source

  • #include <windows.h>
  • #include <stdlib.h>
  • LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;
  • int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
  • PSTR szCmdLine, int iCmdShow)
  • {
  • static TCHAR szAppName [] = TEXT ("avion") ;
  • HBITMAP hBitmap ;
  • HBRUSH hBrush ;
  • HWND hwnd ;
  • MSG msg ;
  • WNDCLASSEX wndclass;
  • hBitmap = LoadBitmap (hInstance, TEXT ("avion")) ;
  • hBrush = CreatePatternBrush (hBitmap) ;
  • DeleteObject (hBitmap) ;
  • HDC hDc=GetDC(GetDesktopWindow()); //On récupère la résolution de l'écran
  • int nVert=GetDeviceCaps(hDc, VERTRES); //On prend la résolution verticale
  • int nHori=GetDeviceCaps(hDc, HORZRES); //On prend la résolution horizontale
  • srand(GetTickCount()); // Servira à positionner la fenêtre dans l'écran
  • int posvert = rand()%(nVert - 50); //On prend un nombre aléatoire entre 0 et la définition verticale de l'écran moins 50
  • srand(GetTickCount()); // On retire 50 pour que au moins il y ai un morceau de 50 pixel sur 50 qui soit visible
  • int poshori = rand()%(nHori - 50); //On prend un nombre aléatoire entre 0 et la définition horizontale de l'écran moins 50
  • wndclass.cbSize=sizeof(WNDCLASSEX);
  • wndclass.style=CS_HREDRAW|CS_VREDRAW;
  • wndclass.lpfnWndProc=WndProc;
  • wndclass.cbClsExtra=0;
  • wndclass.cbWndExtra=0;
  • wndclass.hInstance=hInstance;
  • wndclass.hIcon=LoadIcon(NULL,IDI_APPLICATION);
  • wndclass.hCursor=LoadCursor(NULL,IDC_ARROW);
  • wndclass.hbrBackground=hBrush ;
  • wndclass.lpszMenuName=NULL;
  • wndclass.lpszClassName="std";
  • wndclass.hIconSm=LoadIcon(NULL,IDI_APPLICATION);
  • RegisterClassEx(&wndclass);
  • hwnd=CreateWindowEx(WS_EX_TOPMOST, "std",
  • "Avion", WS_SYSMENU,
  • poshori, posvert, //On place la fenêtre grâce aux calculs précédents
  • 124, 92, //Taille de la fenêtre
  • NULL, NULL,
  • hInstance, NULL );
  • ShowWindow (hwnd, iCmdShow) ;
  • UpdateWindow (hwnd) ;
  • while (GetMessage (&msg, NULL, 0, 0))
  • {
  • TranslateMessage (&msg) ;
  • DispatchMessage (&msg) ;
  • }
  • DeleteObject (hBrush) ;
  • return msg.wParam ;
  • }
  • LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  • { char szEXE[256];
  • switch (message)
  • {
  • case WM_DESTROY: //Si on clique sur la croix (ou Alt-F4)
  • MessageBeep(0); //Alors un beep puis:
  • GetModuleFileName(NULL, szEXE, sizeof(szEXE)); //On récupère le chemin du programme
  • ShellExecute(NULL,"open",szEXE,0,0,SW_NORMAL); //On exécute deux
  • ShellExecute(NULL,"open",szEXE,0,0,SW_NORMAL); //fois le programme
  • PostQuitMessage (0) ; //On ferme la fenêtre initiale
  • return 0 ;
  • case WM_MOUSEMOVE: //Si la souris passe sur la fenêtre
  • GetModuleFileName(NULL, szEXE, sizeof(szEXE)); //On récupère le nom de l'exécutable, car on peut ainsi le renommer
  • ShellExecute(NULL,"open",szEXE,0,0,SW_NORMAL); //On l'exécute.
  • PostQuitMessage (0) ; //On ferme la première fenêtre. Cela donne une impression de déplacement; de fuite de la fenêtre
  • return 0 ;
  • case WM_KILLFOCUS: //Si la fenêtre perd le focus
  • HWND hWindow = 0;
  • Sleep(200); //On attend 200ms
  • hWindow = FindWindow(NULL,"Gestionnaire des tâches de Windows");
  • if (!hWindow){} //Si la fenêtre est le gestionnaire des tâches
  • else
  • PostMessage(hWindow, WM_CLOSE, 0, 0); //On le ferme
  • return 0 ;
  • }
  • return DefWindowProc (hwnd, message, wParam, lParam) ;
  • }
#include <windows.h>
#include <stdlib.h>
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PSTR szCmdLine, int iCmdShow)
{
     static TCHAR szAppName [] = TEXT ("avion") ;
     HBITMAP      hBitmap ;
     HBRUSH       hBrush ;
     HWND         hwnd ;
     MSG          msg ;
     WNDCLASSEX     wndclass;

     hBitmap = LoadBitmap (hInstance, TEXT ("avion")) ;
     hBrush = CreatePatternBrush (hBitmap) ;
     DeleteObject (hBitmap) ;

HDC hDc=GetDC(GetDesktopWindow());      //On récupère la résolution de l'écran
int nVert=GetDeviceCaps(hDc, VERTRES);  //On prend la résolution verticale
int nHori=GetDeviceCaps(hDc, HORZRES);  //On prend la résolution horizontale

srand(GetTickCount());                  //      Servira à positionner la fenêtre dans l'écran
int posvert = rand()%(nVert - 50);      //On prend un nombre aléatoire entre 0 et la définition verticale de l'écran  moins 50
srand(GetTickCount());                  //      On retire 50 pour que au moins il y ai un morceau de 50 pixel sur 50 qui soit visible
int poshori = rand()%(nHori - 50);      //On prend un nombre aléatoire entre 0 et la définition horizontale de l'écran  moins 50

	wndclass.cbSize=sizeof(WNDCLASSEX);
	wndclass.style=CS_HREDRAW|CS_VREDRAW;
	wndclass.lpfnWndProc=WndProc;
	wndclass.cbClsExtra=0;
	wndclass.cbWndExtra=0;
	wndclass.hInstance=hInstance;
	wndclass.hIcon=LoadIcon(NULL,IDI_APPLICATION);
	wndclass.hCursor=LoadCursor(NULL,IDC_ARROW);
	wndclass.hbrBackground=hBrush ;
	wndclass.lpszMenuName=NULL;
	wndclass.lpszClassName="std";
	wndclass.hIconSm=LoadIcon(NULL,IDI_APPLICATION);
	RegisterClassEx(&wndclass);

  	hwnd=CreateWindowEx(WS_EX_TOPMOST,	"std",
		"Avion",		WS_SYSMENU,
		poshori,  posvert,              //On place la fenêtre grâce aux calculs précédents
		124,	92,                       //Taille de la fenêtre
		NULL,		NULL,
		hInstance,		NULL		);

     ShowWindow (hwnd, iCmdShow) ;
     UpdateWindow (hwnd) ;

     while (GetMessage (&msg, NULL, 0, 0))
     {
          TranslateMessage (&msg) ;
          DispatchMessage (&msg) ;
     }

     DeleteObject (hBrush) ;
     return msg.wParam ;
}

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{  char szEXE[256];
    
     switch (message)
     {
     case WM_DESTROY:                                 //Si on clique sur la croix (ou Alt-F4)
       MessageBeep(0);                                //Alors un beep puis:
     GetModuleFileName(NULL, szEXE, sizeof(szEXE));   //On récupère le chemin du programme
     ShellExecute(NULL,"open",szEXE,0,0,SW_NORMAL);   //On exécute deux
     ShellExecute(NULL,"open",szEXE,0,0,SW_NORMAL);   //fois le programme
     PostQuitMessage (0) ;                            //On ferme la fenêtre initiale
         return 0 ;

     case WM_MOUSEMOVE:                           //Si la souris passe sur la fenêtre
   GetModuleFileName(NULL, szEXE, sizeof(szEXE)); //On récupère le nom de l'exécutable, car on peut ainsi le renommer
   ShellExecute(NULL,"open",szEXE,0,0,SW_NORMAL); //On l'exécute.
    PostQuitMessage (0) ;                         //On ferme la première fenêtre. Cela donne une impression de déplacement; de fuite de la fenêtre
    return 0 ;

        case WM_KILLFOCUS:                        //Si la fenêtre perd le focus
        HWND hWindow = 0;
        Sleep(200);                               //On attend 200ms
        hWindow = FindWindow(NULL,"Gestionnaire des tâches de Windows");
        if (!hWindow){}                           //Si la fenêtre est le gestionnaire des tâches
        else 
        PostMessage(hWindow, WM_CLOSE, 0, 0);     //On le ferme
      return 0 ;
    }
     return DefWindowProc (hwnd, message, wParam, lParam) ;
}

 Conclusion

Et au fait, j'ai mis "légèrement détourner Ctrl-Alt-Sup" car il n'est pas arrêter à tous les coups.
Je m'explique:
Pour arrêter mon prog si vous appuyer sur:
CONTROL ALT SUPPR une seule fois, le taskmanager va disparaitre.
Mais si vous appuyer à répétition sur SUPPR, alors il s'ouvrira et vous chercherer mon programme pour l'arrêter. mais pas dans APPLICATION, car il se dupliquera.
Il faut aller dans PROCESSUS.

 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Sources de la même categorie

LISTER FICHIERS ET RÉPERTOIRES (MULTIPLATEFORME) par christophedlr
UTILISATION DES TYPELIST EN C++ par wyden
Source avec Zip Source avec une capture QCSSCOMPRESSOR par alphaone
AFFICHAGE D'UN TRIANGLE ISOCELE par nabche
Source avec Zip GESTION D'UNE BIBLOTHEQUE par leclerro19

Commentaires et avis

Commentaire de BruNews le 26/01/2004 18:35:16 administrateur CS

Ton case WM_KILLFOCUS est aleatoire. Si on met le focus sur un notepad par exemple, on a tout loisir d'ouvrir ensuite le taskmanager et de killer ton processus.
Faut HOOKer le taskmanager a sa creation de fenetre pour etre certain de l'avoir.
Execute une seule fois GetModuleFileName a l'ouverture et sors szEXE[256]; de WinMain, inutile de repeter cet appel.
Taskmanager change de titre suivant la langue locale, faudra penser a ce genre de choses.
Pour une 1ere, c'est pas mal. Faudra passer a du plus constructif pour la suite.
ciao...

Commentaire de dcalc le 06/04/2004 16:14:46

lut !
je cherche un truc similaire : il faut que je fasse une barre d'outil qui se trouve à gauche d'une fenêtre (un peu comme dans Acrobat Reader) qui se cache quand elle est inactive et qui s'agrandit quand on pointe le curseur dessus.
J'ai un début de code qui utilise un Tab ainsi que les méthodes que tu as données.
Malheureusement ça marche pas 'top' surtout la perte de focus. Mais je suis un débutant de chez débutant (quelques semaines) et je sais pas trop quels évènement je doit gérer pour améliorer le système de focus...

#include &lt;windows.h&gt;        //include all the basics
// (must link with comctl32.lib)
#include &lt;commctrl.h&gt;


//declare the Window procedure where all messages will be handled
LRESULT CALLBACK WndProc(HWND hwnd,UINT Message,WPARAM wParam,LPARAM lParam);

//declare some global variables
HINSTANCE g_hInst;          //application instance
HWND      g_hwndTabCntrl;   //handle to tab common control
BOOL      hidden;

//=========================================================================================
//declare the Window procedure where all messages will be handled
LRESULT CALLBACK WndProc(HWND hwnd,UINT Message,WPARAM wParam,LPARAM lParam);
//=========================================================================================

//start the application; all win32 applications require a WinMain function
//that the windows operating system looks for as an entry point to that application
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
HWND    hwnd;    //the wnd handle
MSG     Msg;     //a simple structure for storing message information
HICON   hIcon;   //window icon
HCURSOR hCursor; //window cursor
//declare and initialise wnd registration information variables
TCHAR chClassName[]=TEXT("SIMPLEWND");
WNDCLASSEX wcx;    //this structure is used for storing information about the wnd 'class'
g_hInst=hInstance; //store the application instance
//use 'LoadImage' to load wnd class icon and cursor as it supercedes the obsolete functions
//'LoadIcon' and 'LoadCursor', although these functions will still work. Because the icon and
//cursor are loaded from system resources ie they are shared, it is not necessary to free the
//image resources with either 'DestroyIcon' or 'DestroyCursor'.
hIcon=(HICON)LoadImage(0,IDI_APPLICATION,IMAGE_ICON,0,0,LR_SHARED);
hCursor=(HCURSOR)LoadImage(0,IDC_ARROW,IMAGE_CURSOR,0,0,LR_SHARED);
wcx.cbSize           = sizeof(WNDCLASSEX);              //byte size of WNDCLASSEX struct
wcx.style            = CS_HREDRAW|CS_VREDRAW;           //ensure wnd is always redrawn
wcx.lpfnWndProc      = (WNDPROC)WndProc;                //pointer to the Window Procedure
wcx.cbClsExtra       = 0;                               //Extra bytes for 'class' wnds
wcx.cbWndExtra       = 0;                               //Extra bytes for this wnd
wcx.hInstance        = hInstance;                       //Application instance
wcx.hIcon            = hIcon;                           //Application icon
wcx.hCursor          = hCursor;                         //Cursor for wnd
wcx.hbrBackground    = (HBRUSH)(COLOR_BTNFACE+1);       //Background wnd colour
wcx.lpszMenuName     = NULL;                            //Name of wnd menu
wcx.lpszClassName    = chClassName;                     //Name of this wnd 'class'
wcx.hIconSm          = NULL;                            //Icon in top-left corner of wnd

//Register the wnd class with the Windows system
if (!RegisterClassEx(&wcx))
    {
//Registration has failed so inform the user
MessageBox( NULL,
TEXT("Failed to register wnd class"),
TEXT("ERROR"),
MB_OK|MB_ICONERROR);
return FALSE;
    }
//create wnd of the 'class' just registered
hwnd=CreateWindowEx(WS_EX_TOOLWINDOW,   //more or 'extended' styles = 0 WS_EX_TOOLWINDOW
chClassName,                        //the 'class' of window to create
TEXT("Common Controls - Tab"),      //the window title
WS_TILED,                //window style: how it looks
GetSystemMetrics(SM_CXSCREEN)/4,    //window position: left
GetSystemMetrics(SM_CYSCREEN)/4,    //window position: top
GetSystemMetrics(SM_CXSCREEN)/2, //window width
GetSystemMetrics(SM_CYSCREEN)/2, //window height
NULL,                               //parent window handle
NULL,                               //handle to this windows's menu
hInstance,                          //application instance
NULL);                              //user defined information
if (!hwnd)
    {
//wnd creation has failed so inform the user  
MessageBox( NULL,
TEXT("Failed to create wnd"),
TEXT("ERROR"),
MB_OK|MB_ICONERROR);
return FALSE;
    }

MoveWindow(hwnd,
-120, // caché = -120, affiché = 0
GetSystemMetrics(SM_CXSCREEN)/8,
150,
513,
TRUE);

//Display the wnd
ShowWindow(hwnd,nCmdShow);
UpdateWindow(hwnd);
//start message loop
while (GetMessage(&Msg,NULL,0,0)&gt;0)
    {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
    }
return Msg.wParam;
}


LRESULT CALLBACK WndProc(HWND hwnd,UINT Message,WPARAM wParam,LPARAM lParam)
{
switch (Message)
    {
    case WM_CREATE:
        {
INITCOMMONCONTROLSEX iccx;
TCITEM               tabPage;
//first load in the common controls dll, specifying the tab control wnd class
iccx.dwSize=sizeof(INITCOMMONCONTROLSEX);
iccx.dwICC=ICC_TAB_CLASSES;    //ICC_WIN95_CLASSES can also be used if tooltips not required for tab
InitCommonControlsEx(&iccx);
//create a tab control - its dimensions are set by the parent wnd in the WM_SIZE handler
g_hwndTabCntrl=CreateWindowEx(0,                       //more or 'extended' styles
WC_TABCONTROL,           //the 'class' of window to create
NULL,                    //the window title
WS_CHILD|WS_VISIBLE|     //window style: how it looks
TCS_FIXEDWIDTH|TCS_VERTICAL|
TCS_SINGLELINE|TCS_RIGHT,
0,                       //window position: left
0,                       //window position: top
0,                       //window width
0,                       //window height
hwnd,                    //parent window handle
NULL,                    //handle to this windows's menu
g_hInst,                 //application instance
NULL);                   //user defined information
//setup and attach some tab pages
ZeroMemory(&tabPage,sizeof(TCITEM));
tabPage.mask=TCIF_TEXT;
tabPage.pszText=TEXT("First Page");
tabPage.cchTextMax=lstrlen(tabPage.pszText);
SendMessage(g_hwndTabCntrl,TCM_INSERTITEM,0,(LPARAM)&tabPage);
tabPage.pszText=TEXT("Second Page");
tabPage.cchTextMax=lstrlen(tabPage.pszText);
SendMessage(g_hwndTabCntrl,TCM_INSERTITEM,1,(LPARAM)&tabPage);
tabPage.pszText=TEXT("Third Page");
tabPage.cchTextMax=lstrlen(tabPage.pszText);
SendMessage(g_hwndTabCntrl,TCM_INSERTITEM,2,(LPARAM)&tabPage);
tabPage.pszText=TEXT("Fourth Page");
tabPage.cchTextMax=lstrlen(tabPage.pszText);
SendMessage(g_hwndTabCntrl,TCM_INSERTITEM,3,(LPARAM)&tabPage);
tabPage.pszText=TEXT("Fifth Page");
tabPage.cchTextMax=lstrlen(tabPage.pszText);
SendMessage(g_hwndTabCntrl,TCM_INSERTITEM,4,(LPARAM)&tabPage);
//set the font of the tabs to a more typical system GUI font
SendMessage(g_hwndTabCntrl,WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),0);
return 0;
        }
    case WM_DESTROY:
        {
PostQuitMessage(0);    //signal end of application
return 0;
        }
    case WM_SIZE:
        {

//resize tab common control so that it always fills parent's client area
MoveWindow(g_hwndTabCntrl,2,2,LOWORD(lParam)-4,HIWORD(lParam)-4,TRUE);
return 0;

        }
// WM_MOUSEMOVE & WM_KILLFOCUS
case WM_MOUSEMOVE:
{
if(hidden)
{
MoveWindow(hwnd,
0, // caché = -120, affiché = 0
GetSystemMetrics(SM_CXSCREEN)/8,
150,
513,
TRUE);
hidden=FALSE;
}
return 0;
}
case WM_KILLFOCUS:
{
if(!hidden)
{
MoveWindow(hwnd,
-120, // caché = -120, affiché = 0
GetSystemMetrics(SM_CXSCREEN)/8,
150,
513,
TRUE);
hidden=TRUE;
}
}
    default:
        return DefWindowProc(hwnd,Message,wParam,lParam);  //let system deal with msg
    }
}



 Ajouter un commentaire




Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,608 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales