Low high order word

  • Remove From My Forums
  • Question

  • I see often the reference to low or high order word when it comes to
    lParam
    . Does it mean that lParam has two values at the same time distinguished by which side in allocated memory for that variable each of them occupies (for example left-first byte is low word/right second byte is high
    word) or it means that lParam can contain either one of the formats (not both at once) depending on the functionality that places it into lParam (big endian value or little endian value)?

Answers

  • In a Win32 context lParam is 32 bits.  «Word» is 16 bits, so two words can fit into a 32 bit location at the same time.  The «low» word is the least significant 16 bits.  The «high» word is the most significant 16 bits. 

    Notice that «bytes» and «endianness» have nothing to do with this.  No matter where or how the low word is stored in memory it is still the low (meaning least significant) word.

    • Marked as answer by

      Monday, July 19, 2010 12:12 AM

  • >I see often the reference to low or high order word when it comes to
    lParam
    . Does it mean that lParam has two values at the same time distinguished by which side in allocated memory for that variable each of them occupies (for example left-first byte is low word/right second byte is high
    word) or it means that lParam can contain either one of the formats (not both at once) depending on the functionality that places it into lParam (big endian value or little endian value)?

    An LPARAM value is a 32-bit value in a 32-bit world (and old 16-bit
    Windows), and a 64-bit value in the 64-bit world.

    I guess you’re referring to the 16/32-bit world where it was often
    used (in 16-bit Windows) to hold 2 16-bit values (a WORD is defined as
    a 16-bit value) — often in conjunction with the helper macros LOWORD &
    HIWORD.

    Does that clarify things a little?

    Dave

    • Marked as answer by
      Victor Stout
      Monday, July 19, 2010 12:12 AM

  • Home
  • VBForums
  • Visual Basic
  • API
  • What are «high order» and «low order» words?

  1. Sep 22nd, 2004, 02:08 AM


    #1

    odedyer is offline

    Thread Starter


    Junior Member


    What are «high order» and «low order» words?

    I ran into these terms when I started reading about API. Can you tell me what they mean? Please be as popular as you can with your explanation, I don’t know many other terms when talking about API…


  2. Sep 22nd, 2004, 03:32 AM


    #2

    A long integer («Long» in VB) takes up 32 bits of memory.
    An word («integer» in VB6)takes up 16 bits

    This means that you can fit two words in the same space as would be taken by one long integer.

    The windows API uses this to pass two word parameters to a function that normally takes one long integer.

    To seperate this long integer into two words you take the first 16 bits into one word (the «high word») and the second 16 bits into the other word (the «low word»).


  3. Sep 22nd, 2004, 08:43 AM


    #3

    cjqp is offline


    Hyperactive Member


    What would be the easiest way to separate these?

    cjqp

    When your answer is the Arc Sin of 1.015, you should check your Pythagorean triple.


  4. Sep 22nd, 2004, 09:16 AM


    #4

    VB Code:

    1. Option Explicit

    2. '\ Memory manipulation routines

    3. Private Declare Sub CopyMemoryByte Lib "kernel32" Alias "RtlMoveMemory" (Destination As Byte, ByVal Source As Long, ByVal Length As Long)

    4. Private Declare Sub CopyMemoryWord Lib "kernel32" Alias "RtlMoveMemory" (Destination As Integer, ByVal Source As Long, ByVal Length As Long)

    5. Public Function HiByte(ByVal w As Integer) As Byte

    6.     Call CopyMemoryByte(HiByte, VarPtr(w) + 1, 1)

    7. End Function

    8. Public Function LoByte(w As Integer) As Byte

    9.     Call CopyMemoryByte(LoByte, VarPtr(w), 1)

    10. End Function

    11. Public Function LoWord(dw As Long) As Integer

    12. Call CopyMemoryWord(LoWord, VarPtr(dw), 2)

    13. End Function

    14. Public Function HiWord(dw As Long) As Integer

    15. Call CopyMemoryWord(HiWord, VarPtr(dw) + 2, 2)

    16. End Function

    Last edited by Merrion; Sep 22nd, 2004 at 09:39 AM.


  5. Sep 22nd, 2004, 09:22 AM


    #5

    VB Code:

    1. Private Sub Form_Load()

    2.     Dim TestVal As Long, HighInt As Integer, LowInt As Integer

    3.     TestVal = &HF000F000

    4.     'check if the highest bit is active (because Longs are signed)

    5.     If (TestVal And &H80000000) = &H80000000 Then

    6.         'rip 15 bits after the highest bit and activate the highest bit

    7.         HighInt = ((TestVal And &H7FFF0000) &H10000) Or &H8000

    8.     Else

    9.         'rip 15 bits after the highest bit

    10.         HighInt = (TestVal And &H7FFF0000) &H10000

    11.     End If

    12.     'rip lower 16 bits

    13.     LowInt = TestVal Mod &H10000

    14.     'view results

    15.     Debug.Print HighInt, LowInt

    16. End Sub

    You can test what happens when you change TestVal and change HighInt and LowInt to Long datatype.

    Edit Please note doing this without API and/or assigning into a function is far faster than with API or by making a function.


  • Home
  • VBForums
  • Visual Basic
  • API
  • What are «high order» and «low order» words?


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

There are multiple ways of achieving that, here are some of them.


Using the Bitwise and/or Shift operators

Applying a right shift in an integer will move the bits to the right, putting zeros to the left.
In the case below, it will shift the size of a short (Int16, as 16 bits).

Applying a logical AND (&) operation in an integer like 0x0000FFFF will basically ‘cut’ the value (where it’s F) and ignore the rest (where it’s 0).
Remember that in the end it’s just a 0b_1 AND 0b_1 = 0b_1 operation, so any 0b_0 AND 0b_1 will result in 0b_0.

Applying a logical OR (|) operation will basically merge the two numbers in this case, like 0b_10 | 0b_01 = 0b_11.

Code:

uint number = 0xDEADBEEF;

//Get the higher order value.
var high = number >> 16;
Console.WriteLine($"High: {high:X}");

//Get the lower order value.
var low = number & 0xFFFF; //Or use 0x0000FFFF
Console.WriteLine($"Low: {low:X}");

//Set a high order value (you can also use 0xFFFF instead of 0x0000FFFF).
uint newHigh = 0xFADE;
number = number & 0x0000FFFF | newHigh << 16;
Console.WriteLine($"New high: {number:X}");

//Set a low order value.
uint newLow = 0xC0DE;
number = number & 0xFFFF0000 | newLow & 0x0000FFFF;
Console.WriteLine($"New low: {number:X}");

Output:

High: DEAD
Low: BEEF
New high: FADEBEEF
New low: FADEC0DE

Using FieldOffsetAttribute in a struct

C# has excellent support for variables sharing the same memory location, and bits structuring.

Since C# has no macro functions like in C, you can use the union approach to speed things up. It’s more performant than passing the variable to methods or extension methods.

You can do that by simply creating a struct with explicit layout and setting the offset of the fields:

Code:

using System;
using System.Runtime.InteropServices;
   
[StructLayout(LayoutKind.Explicit)]
struct WordUnion
{
    [FieldOffset(0)]
    public uint Number;

    [FieldOffset(0)]
    public ushort Low;

    [FieldOffset(2)]
    public ushort High;
}
    
public class MainClass
{
    public static void Main(string[] args)
    {        
        var x = new WordUnion { Number = 0xABADF00D };
        Console.WriteLine("{0:X} {1:X} {2:X}", x.Number, x.High, x.Low);

        x.Low = 0xFACE;
        Console.WriteLine("{0:X} {1:X} {2:X}", x.Number, x.High, x.Low);

        x.High = 0xDEAD;
        Console.WriteLine("{0:X} {1:X} {2:X}", x.Number, x.High, x.Low);
    }
}

Output:

ABADF00D ABAD F00D
ABADFACE ABAD FACE
DEADFACE DEAD FACE

Mind that with Visual Studio 2029 (16.7), you still may get zeros in x.High and x.Low when adding the variable x inside the Watch or by hovering your cursor on top of the variables x.High and x.Low directly.

Visual Studio Bug


Using unsafe and pointer element access operator []

To a more akin to C programming, but in C#, use unsafe:

Code:

unsafe
{
    uint value = 0xCAFEFEED;

    // x86 is using low-endian. 
    // So low order array number gets the low order of the value
    // And high order array number gets the high order of the value
    Console.WriteLine("Get low order of {0:X}: {1:X}", 
        value, ((ushort*) &value)[0]);

    Console.WriteLine("Get high order of {0:X}: {1:X}", 
        value, ((ushort*) &value)[1]);


    ((ushort*) &value)[1] = 0xABAD;
    Console.WriteLine("Set high order to ABAD: {0:X}", value);

    ((ushort*) &value)[0] = 0xFACE;
    Console.WriteLine("Set low order to FACE: {0:X}", value);
}

Output:

Get low order of CAFEFEED: FEED
Get high order of CAFEFEED: CAFE
Set high order to ABAD: ABADFEED
Set low order to FACE: ABADFACE

Using unsafe and pointer member access operator ->

Another unsafe approach, but this time accessing a member from the WordUnion struct declared in a previous example:

Code:

unsafe
{
    uint value = 0xCAFEFEED;

    Console.WriteLine("Get low order of {0:X}: {1:X}", 
        value, ((WordUnion*) &value)->Low);

    Console.WriteLine("Get high order of {0:X}: {1:X}", 
        value, ((WordUnion*) &value)->High);


    ((WordUnion*) &value)->High = 0xABAD;
    Console.WriteLine($"Set high order to ABAD: {value:X}");

    ((WordUnion*) &value)->Low = 0xFACE;
    Console.WriteLine($"Set low order to FACE: {value:X}");
}

Output:

Get low order of CAFEFEED: FEED
Get high order of CAFEFEED: CAFE
Set high order to ABAD: ABADFEED
Set low order to FACE: ABADFACE

Using the BitConverter class

It simply gets 16 bits (2 bytes, a short/Int16) from the specified number. The offset can be controlled by the second parameter.

Code:

uint value = 0xCAFEFEED;

var low = BitConverter.ToInt16(BitConverter.GetBytes(value), 0);
var high = BitConverter.ToInt16(BitConverter.GetBytes(value), 2);

Console.WriteLine($"Low: {low:X}");
Console.WriteLine($"High: {high:X}");

Output:

Low: 0xCAFE
High: 0xFEED

 
tytus
 
(2006-05-12 13:51)
[0]

Доброго дня ВСЕМ! Мне нужно в программе проверять, правильно ли пользователь выбрал файл — должен быть текстовый. Делаю так:
function TMainFm.CheckFileValid(AFileName:string):boolean;
var
 CData:PByte;
 CHandle,CType,CFileSize,CMapHandle:Cardinal;
 CFileInfo:BY_HANDLE_FILE_INFORMATION;
 Count,CharCount:integer;
begin
CHandle:=CreateFile(PChar(AFileName),GENERIC_READ,
     0,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if CHandle=0 then
 begin
   MessageBox(Handle,»Error»,PChar(«Failed to open file»+#13+#10+
   AFileName),MB_OK);
   RaiseLastOsError;
   exit;
 end;
GetFileInformationByHandle(CHandle,CFileInfo);
CFileSize:=CFileInfo.nFileSizeLow+CFileInfo.nFileSizeHigh;
Count:=0;
CharCount:=0;
CMapHandle:=CreateFileMapping(CHandle,nil,PAGE_READONLY,0,CFileSize,nil);
CData:=MapViewOfFile(CMapHandle,FILE_MAP_READ,0,0,CFileSize);
while Count<CFileSize do
 begin
   if (CData^>31)or(CData^ in[$0D,$0A]) then inc(CharCount);
   inc(CData);
   inc(Count);
 end;
Result:=Count=CharCount;
UnMapViewOfFile(CData);
CloseHandle(CMapHandle);
CloseHandle(CHandle);
end;
Может есть способ по проще?


 
Сергей М. ©
 
(2006-05-12 13:57)
[1]


> CFileSize:=CFileInfo.nFileSizeLow+CFileInfo.nFileSizeHigh

Это

даст ошибку для любого файла размером более 65535 байт.

Читай справку и думай.


 
Jeer ©
 
(2006-05-12 13:57)
[2]

Текстовый файл из одной строки без CRLF —  тоже текстовый.


 
Сергей М. ©
 
(2006-05-12 13:58)
[3]

+ файл в формате Unicode — тоже текстовый


 
begin…end ©
 
(2006-05-12 14:05)
[4]

> Сергей М. ©   (12.05.06 13:57) [1]

4294967295


 
tytus
 
(2006-05-12 14:06)
[5]

>Сергей М [1]
Ничего попдобного. Делаю так уже давно, файлы открываются ЛЮБОГО размера!!!


 
balepa ©
 
(2006-05-12 14:07)
[6]

А может просто давать открывать только .txt ?


 
tytus
 
(2006-05-12 14:08)
[7]

Ну так что, НЕТУ варианта по проще и достовернее!?
и ище — [1] файл размером около 140 метров проверяется МГНОВЕННОООО!


 
tytus
 
(2006-05-12 14:11)
[8]

>balera [6]
файл может иметь ЛЮБОЕ расширение (*.trf, *.bin etc), главное чтобы его содержимое можно было просмотреть БЛОКНОТОМ или ВОРДПАДОМ.


 
Сергей М. ©
 
(2006-05-12 14:14)
[9]

Ничего не знаю.

Цитата из MSDN:

nFileSizeHigh

Specifies the high-order word of the file size.

Нет никаких сведений о сдвиге этого самого high-order word в поле nFileSizeHigh на 16 разрядов влево


 
begin…end ©
 
(2006-05-12 14:18)
[10]

> Сергей М. ©   (12.05.06 14:14) [9]

У Вас неправильный MSDN.

nFileSizeHigh
 High-order part of the file size.
nFileSizeLow
 Low-order part of the file size.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/by_handle_file_information_str.asp


 
Jeer ©
 
(2006-05-12 14:18)
[11]

tytus   (12.05.06 14:11) [8]

А ты попробуй открыть в notepad не текстовый файл и удивишься — откроется.


 
tytus
 
(2006-05-12 14:18)
[12]

>[9]
Проще всего отмахаться и не проверить!!! Я поражаюсь твоей ленью!
Код в начале ветки — скопируй (даже набирать ничего не надо !!!) и проверь!
Ежели не интересно — тогда другое дело, я бы на твоем месте разобрался…


 
Сергей М. ©
 
(2006-05-12 14:20)
[13]


> begin…end ©   (12.05.06 14:18) [10]

Точно такой же как у тебя.

И где там сказано про сдвиг ?


 
begin…end ©
 
(2006-05-12 14:21)
[14]

> Сергей М. ©   (12.05.06 14:20) [13]

> Точно такой же как у тебя.
Судя по различию текстов, не такой же.

> И где там сказано про сдвиг ?
Нигде. А про какой сдвиг там должно быть сказано?


 
tytus
 
(2006-05-12 14:21)
[15]

>Jeer [11]
Да… удивил -)))) спасибо за совет -))))
Блокнотом можно и MP3 ( да что там — VOB) просматривать!!!
Господа, спасибо всем за внимание, но МЫ НЕмного отвлеклись…


 
Сергей М. ©
 
(2006-05-12 14:22)
[16]


> tytus   (12.05.06 14:18) [12]


> не интересно — тогда другое дело

Действительно не интересно.

Был бы у тебя OR вместо «+» , я бы даже не обратил на это внимания.


 
Пусик ©
 
(2006-05-12 14:23)
[17]


> Сергей М. ©   (12.05.06 13:57) [1]
>
>
> > CFileSize:=CFileInfo.nFileSizeLow+CFileInfo.nFileSizeHigh
>
>
> Это даст ошибку для любого файла размером более 65535 байт.
>

Для файлов больше 2-х Гигабайт.
> tytus   (12.05.06 14:08) [7]
>
> Ну так что, НЕТУ варианта по проще и достовернее!?

У тебя достаточно оптимальный код.
Но алгоритм проверки на текст немного неверный.

Кроме #13#10 практически в любом текстовм файл встретишь #09 — TAB.
Для определения, текстовый файл или нет, не обязательно проверять весь файл.
Для того, чтобы файл был тектовым, не нужно условие, чтобы все 100% файла были отображаемыми символами. Сколько в процентном соотношении тебя устроит — определи сам, тестируя на разных файлах.

Кроме того:

CFileSize: int64;

CFileSize:=CFileInfo.nFileSizeLow+(Int64(CFileInfo.nFileSizeHigh) shl 32);


 
Jeer ©
 
(2006-05-12 14:24)
[18]

tytus   (12.05.06 14:21) [15]

Да какая разница — работает и ладно.
Вот если бы не работало.


 
tytus
 
(2006-05-12 14:28)
[19]

>[17]
Да, Пусик, полностью  стобой согласен.
Просто в требуемых для обработки файлах ТОЧНО не встретится символ
табуляции — это 100 проц.
Кроме того, файлы 100 проц. текстовые, и соотношение мне ненужно, в этом скорее всего даже выгода есть определенная.


 
Сергей М. ©
 
(2006-05-12 14:29)
[20]


> begin…end ©   (12.05.06 14:21) [14]
> Судя по различию текстов, не такой же.

Справка от Борланда в этом контексте смыслом не отличается, согласен ?


> ро какой сдвиг там должно быть сказано?

Про тот самый ..

Для файла размером, скажем, 70000 байт значение High-order part должно быть равно $00000001, а не $00010000


 
tytus
 
(2006-05-12 14:30)
[21]

>ALL. спасибо ВСЕМ, кто был неравнодушен к моему вопросу!
Если что — пишите.


 
atruhin ©
 
(2006-05-12 14:31)
[22]

Абсолютно ненужная проверка! Если бы это можно было достоверно проверить…. :). Например файл в дос кодировке с таблицами в псевдографике, может использовать почти все 256 сиволов.


 
Jeer ©
 
(2006-05-12 14:31)
[23]

Пробный текстовый файл ?  :))


 
begin…end ©
 
(2006-05-12 14:36)
[24]

> Пусик ©   (12.05.06 14:23) [17]

Лучше так:

Int64Rec(CFileSize).Lo := CFileInfo.nFileSizeLow;
Int64Rec(CFileSize).Hi := CFileInfo.nFileSizeHigh;

> Сергей М. ©   (12.05.06 14:29) [20]

> Справка от Борланда в этом контексте смыслом не отличается,
> согласен ?

Как же не отличается? В ней говорится про low/high-order word, а в MSDN — про low/high-order part. И если

32-битный

параметр называется

младшей ЧАСТЬЮ

размера файла, то я не вижу причин для того, чтобы считать действительными только 16 бит.

> Для файла размером, скажем, 70000 байт значение High-order
> part должно быть равно $00000001, а не $00010000

Для файла размером в 70000 байт значение high-order part должно быть равно нулю.


 
Сергей М. ©
 
(2006-05-12 14:38)
[25]


> Пусик ©   (12.05.06 14:23) [17]


> Для файлов больше 2-х Гигабайт

При Int64 это будет всего лишь «ругань» компилятора, не более того.


 
tytus
 
(2006-05-12 14:40)
[26]

>atruhin [22]
Псевдографика — это ///\|||||—-____, дык проверяется …
>jeer [23] ВОТ ОНО:
06-05-0900:151    481 139113496874   60    0    0       0000000000002 1391       0    0    0    0       0000000000003 1391       0    4    4    0       0000000000004 1391       0    0    0    0       4000000000005 1391       0  120    0    0       0000000000006 1391       0    0    0    0       0000000000007 1391     189    4    0    4       001600000000
06-05-0900:301    481 139113497209   60    0    0       0000000000002 1391       0    0    0    0       0000000000003 1391       0   18   18    0       0000000000004 1391       0    0    0    0      18000000000005 1391       0  121    0    0       0000000000006 1391       0    0    0    0       0000000000007 1391     235   18    0   18       001600000000 И ТАК ДАЛЕЕ — около 34 кило.
Открыто супер просмотрщиком файлов — БЛОКНОТ-ом!


 
Сергей М. ©
 
(2006-05-12 14:46)
[27]


> Для файла размером в 70000 байт значение high-order part
> должно быть равно нулю

Согласен.
Меня почему-то заклинило на различиях FAT32, где размер файла не может превышать 4ГБ, и, скажем, NTFS, где нет это ограничение отсутствует.

Тем не менее сложение nFileSizeLow nFileSizeHigh бессмысленно для общего случая, при котором размер файла может превышать 4Гб.


 
Игорь Шевченко ©
 
(2006-05-12 14:49)
[28]


> Кроме #13#10 практически в любом текстовм файл встретишь
> #09 — TAB.

Это вряд ли


 
Мефисто
 
(2006-05-12 21:15)
[29]

tytus    (12.05.06 14:30) [21]

Автар не страдайте ерундой.
#13#10
# 09
Могут и в экзешнике попасться без проблем. Без проблем в экзешнике можно и некую текстовую строчку отыскать :)
В данном контексте достоверно проверить является файл текстовым или нет НЕ ВОЗМОЖНО. Воспользоваться вам нужно советом выше. Открывать только файлы с типичным расширением для текстовых файлов. А уж если какойнить изврашенец My.DLL переименовал My.TXT, то уж извеняйте… Программа не телепат…


 
Fay ©
 
(2006-05-13 12:38)
[30]

> if CHandle=0 then
Это чё за хрень? Сравнивать нужно с INVALID_HANDLE_VALUE


 
Eraser ©
 
(2006-05-13 13:56)
[31]


> как проверить что файл текстовый?

по расширению.


 
isasa ©
 
(2006-05-13 15:59)
[32]

По поводу ДОС файлов, в текстовом, может быть и $1A(^Z) и PageBreak, и много чего.
Что считать текстовым файлом(не текстом, как таковым)?


 
isasa ©
 
(2006-05-13 16:03)
[33]

tytus   (12.05.06 14:40) [26]
Я бы проверил на наличие адекватных позиций в колонках, или наличие правильного(одно количества в строке) разделителей.
А файл, не текстовый, а «плоский»(flat в терминах MS SQL), т.е. *.CSV


 
Kolan ©
 
(2006-05-14 13:16)
[34]

Доброго дня ВСЕМ! Мне нужно в программе проверять, правильно ли пользователь выбрал файл — должен быть текстовый. Делаю так:

Не проверяй. Делай то что тебе надо, если не получается(ошибка), то сообщай, что файл неверного формата.
Делается через простой
try
except
end;


 
Мефисто
 
(2006-05-14 18:42)
[35]

Kolan  ©   (14.05.06 13:16) [34]

:)))

>> Делай то что тебе надо,

try
TopenDialog.FileName := «…Word.exe»;

>> если не получается(ошибка)
// А ведь может и получиться :)
TFileStream.WriteBlock(…);

except
>> то сообщай, что файл неверного формата.
// Толи файл не текстовый, толи открыт другим приложением,
// Толи руки кривые, толи лыжи не едут
end;

Причин ошибок может быть куча
>> то сообщай, что файл неверного формата
А заводить пользователя (и себя) в звблуждение не нужно. Ведь ошибки могут бить и при работе с текстовым файлом.

P.S. Нет уж, лучше по старинке оградить пользователя выбором файла определенного файла через TOpenDialog к примеру. А если уж пользователю так хочется любой фалй открыть, так и быть, в списке фильтра оставлю еще масочку типа: *.*


 
Kolan ©
 
(2006-05-14 19:13)
[36]

Мефисто   (14.05.06 18:42) [35]
P.S. Нет уж, лучше по старинке оградить пользователя выбором файла определенного файла через TOpenDialog к примеру. А если уж пользователю так хочется любой фалй открыть, так и быть, в списке фильтра оставлю еще масочку типа: *.*

Так это понятно, тоже всегда так делаю.. А если например Drag»n»Drop.

Просто считаю, что считать символы и в процентах там что-то сравнивать вообше бред.

А в except, извесные типы ошибок. Можно по разному обработать. Ну и тд…


Cursor Arrow And Word Order Stock Illustration - Illustration of ...

src: thumbs.dreamstime.com

In linguistics, word order typology is the study of the order of the syntactic constituents of a language, and how different languages can employ different orders. Correlations between orders found in different syntactic sub-domains are also of interest. The primary word orders that are of interest are the constituent order of a clause — the relative order of subject, object, and verb; the order of modifiers (adjectives, numerals, demonstratives, possessives, and adjuncts) in a noun phrase; and the order of adverbials.

Some languages use relatively restrictive word order, often relying on the order of constituents to convey important grammatical information. Others—often those that convey grammatical information through inflection—allow more flexibility, which can be used to encode pragmatic information such as topicalisation or focus. Most languages, however, have a preferred word order, and other word orders, if used, are considered «marked».

Most nominative-accusative languages—which have a major word class of nouns and clauses that include subject and object—define constituent word order in terms of the finite verb (V) and its arguments, the subject (S), and object (O).

There are six theoretically possible basic word orders for the transitive sentence. The overwhelming majority of the world’s languages are either subject-verb-object (SVO) or subject-object-verb (SOV), with a much smaller but still significant portion using verb-subject-object (VSO) word order. The remaining three arrangements are exceptionally rare, with verb-object-subject (VOS) being slightly more common than object-subject-verb (OSV), and object-verb-subject (OVS) being significantly more rare than the two preceding orders.

Video Word order

Constituent word orders

These are all possible word orders for the subject, verb, and object in the order of most common to rarest (the examples use «she» as the subject, «ate» as the verb, and «bread» as the object):

  • SOV is the order used by the largest number of distinct languages; languages using it include Korean, Mongolian, Turkish, the Indo-Aryan languages and the Dravidian languages. Some, like Persian, Latin and Quechua, have SOV normal word order but conform less to the general tendencies of other such languages. A sentence glossing as «She bread ate» would be grammatically correct in these languages.
  • SVO languages include English, the Romance languages, Bulgarian, Macedonian, Serbo-Croatian, Chinese and Swahili, among others. «She ate bread.»
  • VSO languages include Classical Arabic, the Insular Celtic languages, and Hawaiian. «Ate she bread» is grammatically correct in these languages.
  • VOS languages include Fijian and Malagasy. «Ate bread she.»
  • OVS languages include Hixkaryana. «Bread ate she.»
  • OSV languages include Xavante and Warao. «Bread she ate.»

Sometimes patterns are more complex: German, Dutch, Afrikaans and Frisian have SOV in subordinates, but V2 word order in main clauses, SVO word order being the most common. Using the guidelines above, the unmarked word order is then SVO.

Others, such as Latin, Greek, Persian, Romanian, Assyrian, Turkish, Finnish, and Basque have no strict word order; rather, the sentence structure is highly flexible and reflects the pragmatics of the utterance. Similarly, Japanese requires that all sentences end with V, but it could be SOV or OSV.

Topic-prominent languages organize sentences to emphasize their topic-comment structure. Nonetheless, there is often a preferred order; in Latin and Turkish, SOV is the most frequent outside of poetry, and in Finnish SVO is both the most frequent and obligatory when case marking fails to disambiguate argument roles. Just as languages may have different word orders in different contexts, so may they have both fixed and free word orders. For example, Russian has a relatively fixed SVO word order in transitive clauses, but a much freer SV / VS order in intransitive clauses. Cases like this can be addressed by encoding transitive and intransitive clauses separately, with the symbol ‘S’ being restricted to the argument of an intransitive clause, and ‘A’ for the actor/agent of a transitive clause. (‘O’ for object may be replaced with ‘P’ for ‘patient’ as well.) Thus, Russian is fixed SVO but flexible SV/VS. In such an approach, the description of word order extends more easily to languages that do not meet the criteria in the preceding section. For example, Mayan languages have been described with the rather uncommon VOS word order. However, they are ergative-absolutive languages, and the more specific word order is intransitive VS, transitive VOA, where S and O arguments both trigger the same type of agreement on the verb. Indeed, many languages that some thought had a VOS word order turn out to be ergative like Mayan.

Maps Word order

Functions of constituent word order

A fixed or prototypical word order is one out of many ways to ease the processing of sentence semantics and reducing ambiguity. One method of making the speech stream less open to ambiguity (complete removal of ambiguity is probably impossible) is a fixed order of arguments and other sentence constituents. This works because speech is inherently linear. Another method is to label the constituents in some way, for example with case marking, agreement, or another marker. Fixed word order reduces expressiveness but added marking increases information load in the speech stream, and for these reasons strict word order seldom occurs together with strict morphological marking, one counter-example being Persian.

Observing discourse patterns, it is found that previously given information (topic) tends to precede new information (comment). Furthermore, acting participants (especially humans) are more likely to be talked about (to be topic) than things simply undergoing actions (like oranges being eaten). If acting participants are often topical, and topic tends to be expressed early in the sentence, this entails that acting participants have a tendency to be expressed early in the sentence. This tendency can then grammaticalize to a privileged position in the sentence, the subject.

The mentioned functions of word order can be seen to affect the frequencies of the various word order patterns: The vast majority of languages have an order in which S precedes O and V. Whether V precedes O or O precedes V however, has been shown to be a very telling difference with wide consequences on phrasal word orders.

Knowledge of word order on the other hand can be applied to identify the thematic relations of the NPs in a clause of an unfamiliar language. If we can identify the verb in a clause, and we know that the language is strict accusative SVO, then we know that Grob smock Blug probably means that Grob is the smocker and Blug the entity smocked. However, since very strict word order is rare in practice, such applications of word order studies are rarely effective.

Inverted Word Order: Definition & Examples - Video & Lesson ...

src: study.com

History of constituent word order

A paper by Murray Gell-Mann and Merritt Ruhlen, building on work in comparative linguistics, asserts that the distribution of word order types in the world’s languages was originally SOV. The paper compares a survey of 2135 languages with a «presumed phylogenetic tree» of languages, concluding that changes in word order tend to follow particular pathways, and the transmission of word order is to a great extent vertical (i.e. following the phylogenetic tree of ancestry) as opposed to horizontal (areal, i.e. by diffusion). According to this analysis, the most recent ancestor of currently known languages was spoken recently enough to trace the whole evolutionary path of word order in most cases.

There is speculation on how the Celtic languages developed VSO word order. An Afro-Asiatic substratum has been hypothesized, but current scholarship considers this claim untenable, not least because Afro-Asiatic and Celtic were not in contact in the relevant period.

French basic word order - YouTube

src: i.ytimg.com

Phrase word orders and branching

The order of constituents in a phrase can vary as much as the order of constituents in a clause. Normally, the noun phrase and the adpositional phrase are investigated. Within the noun phrase, one investigates whether the following modifiers occur before or after the head noun.

  • adjective (red house vs house red)
  • determiner (this house vs house this)
  • numeral (two houses vs houses two)
  • possessor (my house vs house my)
  • relative clause (the by me built house vs the house built by me)

Within the adpositional clause, one investigates whether the languages makes use of prepositions (in London), postpositions (London in), or both (normally with different adpositions at both sides).

There are several common correlations between sentence-level word order and phrase-level constituent order. For example, SOV languages generally put modifiers before heads and use postpositions. VSO languages tend to place modifiers after their heads, and use prepositions. For SVO languages, either order is common.

For example, French (SVO) uses prepositions (dans la voiture, à gauche), and places adjectives after (une voiture spacieuse). However, a small class of adjectives generally go before their heads (une grande voiture). On the other hand, in English (also SVO) adjectives almost always go before nouns (a big car), and adverbs can go either way, but initially is more common (greatly improved). (English has a very small number of adjectives that go after their heads, such as extraordinaire, which kept its position when borrowed from French.)

TYP108 - Word Order (International Version) - YouTube

src: i.ytimg.com

Pragmatic word order

Some languages have no fixed word order. These languages often use a significant amount of morphological marking to disambiguate the roles of the arguments. However, some languages use a fixed word order, even if they provide a degree of marking that would support free word order. Also, some languages with free word order—such as some varieties of Datooga—combine free word order with a lack of morphological distinction between arguments.

Typologically there is a trend that highly animate actors are more likely topical than low-animate undergoers, this trend would come through even in free-word-order languages giving a statistical bias for SO order (or OS in the case of ergative systems, however ergative systems do not usually extend to the highest levels of animacy, usually giving way to some form of nominative system at least in the pronominal system). Most languages with a high degree of morphological marking have rather flexible word orders such as Turkish, Latin, Portuguese, Ancient and Modern Greek, Romanian, Hungarian, Lithuanian, Serbo-Croatian, Russian (in intransitive clauses), and Finnish. In some of those, a canonical order can still be identified, but in others this is not possible. When the word order is free, different choices of word order can be used to help identify the theme and the rheme.

Hungarian

In Hungarian, the enclitic -t marks the direct object. For «Kate ate a piece of cake«, the possibilities are:

  • «Kati megevett egy szelet tortát.» (same word order as English) [«Kate ate a piece of cake.«]
  • «Egy szelet tortát Kati evett meg.» (emphasis on agent [Kate]) [«A piece of cake Kate ate.«]
  • «Kati evett meg egy szelet tortát.» (also emphasis on agent [Kate]) [«Kate ate a piece of cake.«]
  • «Kati egy szelet tortát evett meg.» (emphasis on object [cake]) [«Kate a piece of cake ate.»]
  • «Egy szelet tortát evett meg Kati.» (emphasis on number [a piece, i.e. only one piece]) [«A piece of cake ate Kate.»]
  • «Megevett egy szelet tortát Kati.» (emphasis on completeness of action) [«Ate a piece of cake Kate.»]
  • «Megevett Kati egy szelet tortát.» (emphasis on completeness of action) [«Ate Kate a piece of cake.«]

Portuguese

In Portuguese, clitic pronouns and commas allow many different orders:

  • Eu vou entregar para você amanhã. [«I will deliver to you tomorrow.»] (same word order as English)
  • Entregarei para você amanhã. [«{I} will deliver to you tomorrow.»]
  • Eu lhe entregarei amanhã. [«I to you will deliver tomorrow.»]
  • Entregar-lhe-ei amanhã. [«Deliver to you {I} will tomorrow.»] (mesoclisis)
  • A ti, eu entregarei amanhã. [«To you I will deliver tomorrow.»]
  • A ti, entregarei amanhã. [«To you deliver {I} will tomorrow.»]
  • Amanhã, entregarei para você. [«Tomorrow {I} will deliver to you»]
  • Poderia entregar, eu, a você amanhã? [«Could deliver I to you tomorrow?]

Braces ({ }) were used above to indicate omitted subject pronouns, which may be left implicit in Portuguese. Thanks to conjugation, the grammatical person is recovered.

Latin

In Latin, the endings of nouns, verbs, adjectives, and pronouns allow for extremely flexible order in most situations. Latin lacks articles.

The Subject, Verb, and Object can come in any order in a Latin sentence, although most often (especially in subordinate clauses) the verb comes last. Pragmatic factors, such as topic and focus, play a large part in determining the order. Thus the following sentences each answer a different question:

  • Romulus Romam condidit. «Romulus founded Rome» (What did Romulus do?)
  • Hanc urbem condidit Romulus. «Romulus founded this city» (Who founded this city?)
  • Condidit Romam Romulus. «Romulus founded Rome» (What happened?)

Latin prose often follows the word order «Subject, Direct Object, Indirect Object, Adverb, Verb», but this is more of a guideline than a rule. Adjectives in most cases go before the noun they modify, but some categories, such as those that determine or specify (e.g. Via Appia «Appian Way»), usually follow the noun. In Classical Latin poetry, lyricists followed word order very loosely to achieve a desired scansion.

Albanian

Due to the presence of grammatical cases (nominative, genitive, dative, accusative, ablative, and in some cases or dialects vocative and locative) applied to nouns, pronouns and adjectives, the Albanian language permits a large number of positional combination of words. In spoken language a word order differing from the most common S-V-O helps the speaker putting emphasis on a word, thus changing partially the message delivered. Here it is an example:

  • «Marku më dha një dhuratë (mua).» [«Mark (me) gave a present to me.», neutral narrating sentence.]
  • «Marku (mua) më dha një dhuratë.» [«Mark to me (me) gave a present.», emphasis on the indirect object, probably to compare the result of the verb on different persons.]
  • «Marku një dhuratë më dha (mua).» [«Mark a present (me) gave to me», meaning that Mark gave her only a present, and not something else or more presents.]
  • «Marku një dhuratë (mua) më dha.» [«Mark a present to me (me) gave», meaning that Mark gave a present only to her.]
  • «Më dha Marku një dhuratë (mua).» [«Gave Mark to me a present.», neutral sentence, but puts less emphasis on the subject.]
  • «Më dha një dhuratë Marku (mua).» [«Gave a present to me Mark.», probably is the cause of an event being introduced later.]
  • «Më dha (mua) Marku një dhurate.» [«Gave to me Mark a present.», same as above.]
  • «Më dha një dhuratë mua Marku» [«(Me) gave a present to me Mark.», puts emphasis on the fact that the receiver is her and not someone else.]
  • «Një dhuratë më dha Marku (mua)» [«A present gave Mark to me.», meaning it was a present and not something else.]
  • «Një dhuratë Marku më dha (mua)» [«A present Mark gave to me.», puts emphasis on the fact that she got the present and someone else got something different.]
  • «Një dhuratë (mua) më dha Marku.» [«A present to me gave Mark.», no particular emphasis, but can be used to list different actions from different subjects.]
  • «Një dhuratë (mua) Marku më dha.» [«A present to me Mark (me) gave», remembers that at least a present was given to her by Mark.]
  • «Mua më dha Marku një dhuratë.» [«To me (me) gave Mark a present.», is used when Mark gave something else to others.]
  • «Mua një dhuratë më dha Marku.» [«To me a present (me) gave Mark.», emphasis on «to me» and the fact that it was a present, only one present or it was something different from usual.»]
  • «Mua Marku një dhuratë më dha» [«To me Mark a present (me) gave.», Mark gave her only one present.]
  • «Mua Marku më dha një dhuratë» [«To me Mark (me) gave a present.» puts emphasis on Mark. Probably the others didn’t give her present, they gave something else or the present wasn’t expected at all.]

In the aforementioned examples, «(mua)» can be omitted causing a perceivable change in emphasis, the latter being of different intensity. «Më» is always followed by the verb. Thus, a sentence consisting of a subject, a verb and two objects (a direct and an indirect one), can be expressed in six different ways without «mua», and in twenty-four different ways with «mua», adding up to thirty possible combinations.

Indo-Aryan languages

The word order of many Indo-Aryan languages can change depending on what specific implications a speaker wishes to make. These are generally aided by the use of appropriate inflectional suffixes. Consider these examples from Bengali:

  • ??? ??? ???? ??? [«I that don’t know.», typical, neutral sentence]
  • ??? ???? ?? ???? [«I don’t know that.», general emphasis on what isn’t known]
  • ??? ??? ???? ??? [«That I don’t know.», agitation about what isn’t known]
  • ??? ???? ?? ???? [«That don’t know I.», general emphasis on the person who doesn’t know]
  • ???? ?? ??? ???? [«Don’t know I that.», agitation about the person who doesn’t know]
  • *???? ?? ??? ???? [*»Don’t know that I.», unused]

Basic word order in English sentence. worksheet - Free ESL ...

src: en.islcollective.com

Other issues

In many languages, changes in word order occur due to topicalization or in questions. However, most languages are generally assumed to have a basic word order, called the unmarked word order; other, marked word orders can then be used to emphasize a sentence element, to indicate modality (such as an interrogative modality), or for other purposes.

For example, English is SVO (subject-verb-object), as in «I don’t know that», but OSV is also possible: «That I don’t know.» This process is called topic-fronting (or topicalization) and is common. In English, OSV is a marked word order because it emphasises the object, and is often accompanied by a change in intonation.

An example of OSV being used for emphasis:

A: I can’t see Alice. (SVO)
B: What about Bill?
A: Bill I can see. (OSV, rather than I can see Bill, SVO)

Non-standard word orders are also found in poetry in English, particularly archaic or romantic terms — as the wedding phrase «With this ring, I thee wed» (SOV) or «Thee I love» (OSV) — as well as in many other languages.

Translation

Differences in word order complicate translation and language education — in addition to changing the individual words, the order must also be changed. This can be simplified by first translating the individual words, then reordering the sentence, as in interlinear gloss, or by reordering the words prior to translation.

German Word Order - Lessons - Tes Teach

src: i.ytimg.com

See also

  • Anastrophe, change in word order
  • Antisymmetry
  • Information flow

German Grammar: Word Order of Pronouns - YouTube

src: i.ytimg.com

Notes

2 Minute Mechanics - German Word Order - YouTube

src: i.ytimg.com

References

Chinese Grammar Lesson | Chinese word order practice | Yoyo ...

src: i.ytimg.com

Further reading

Source of the article : Wikipedia

Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Люди, кто помнит, как заполнить LOWORD / HIWORD для LPARAM?
Т.е. надо отправить WM_SIZE и указать новые размеры окна.

pDlg->PostMessage(WM_SIZE, wparam, lparam)

WM_SIZE
fwSizeType = wParam;      // resizing flag
nWidth = LOWORD(lParam);  // width of client area
nHeight = HIWORD(lParam); // height of client area
Если просто написать lParam = 50, то получается заполненным соответственно только nWidth   Здесь была моя ладья...

« Последнее редактирование: 17-03-2005 12:52 от Malaja »
Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Pu


а зачем помнить? есть мсдн

WM_SIZE Notification

———————————————————————————

The WM_SIZE message is sent to a window after its size has changed.

A window receives this message through its WindowProc function.

Syntax

WM_SIZE

    WPARAM wParam
    LPARAM lParam;

    Parameters

wParam
Specifies the type of resizing requested. This parameter can be one of the following values.
SIZE_MAXHIDE
Message is sent to all pop-up windows when some other window is maximized.
SIZE_MAXIMIZED
The window has been maximized.
SIZE_MAXSHOW
Message is sent to all pop-up windows when some other window has been restored to its former size.
SIZE_MINIMIZED
The window has been minimized.
SIZE_RESTORED
The window has been resized, but neither the SIZE_MINIMIZED nor SIZE_MAXIMIZED value applies.
lParam
The low-order word of lParam specifies the new width of the client area.
The high-order word of lParam specifies the new height of the client area.


Записан

Насколько я опытен? Достаточно, чтобы понимать, что дураков нельзя заставить думать по–другому, но недостаточно, чтобы отказаться от попыток это сделать.
(с) Артур Джонс

Pu


а заполнить соответственно так —

WORD nWidth = 100; // LOWORD(lParam);   width of client area
WORD nHeight = 200; //HIWORD(lParam);  height of client area
DWORD lParam = nWidth | (nHeight<<16);

« Последнее редактирование: 16-03-2005 10:45 от Pu »
Записан

Насколько я опытен? Достаточно, чтобы понимать, что дураков нельзя заставить думать по–другому, но недостаточно, чтобы отказаться от попыток это сделать.
(с) Артур Джонс

Pu


а еще есть такой макрос —

LPARAM MAKELPARAM(
    WORD wLow,
    WORD wHigh
);

nWidth = 100; // LOWORD(lParam);   width of client area
nHeight = 200; //HIWORD(lParam);  height of client area
lParam = MAKELPARAM( nWidth, nHeight);

#define MAKELONG(a, b)      ((LONG)(((WORD)((DWORD_PTR)(a) & 0xffff)) | ((DWORD)((WORD)((DWORD_PTR)(b) & 0xffff))) << 16))
#define MAKELPARAM(l, h)      ((LPARAM)(DWORD)MAKELONG(l, h))


Записан

Насколько я опытен? Достаточно, чтобы понимать, что дураков нельзя заставить думать по–другому, но недостаточно, чтобы отказаться от попыток это сделать.
(с) Артур Джонс

Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Заяц, миленький, я тебя обожаю! Ага Именно этот макрос я и искала, т.е. я помнила, что он был, но как его звали — не помнила! А что касается побитовых сдвижек, тут я просто пас — ну просачковала я еще на лекзиях эту тему, а потом нигде не надо было, посему я это никогда не помню Ага Говорю же — я женщина забывчивая Ага


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Упс, а wm_size что-то не работает. ;-(
Создала обычное mdi — приложение, в нем создала диалог как popup / dialog frame, в котором толко title bar есть. Стартую его как немодальный из View, при старте перемещаю в правый верхний угол основного приложения и хочу задать ему определенные размеры. Но это ничего не дает — т.е. окно перемещается куда надо, а вот размеры остаются неизменными. А почему — не пойму… ;-(

   LPARAM lparam = MAKELPARAM(50, 50);
   WPARAM wParam = (WPARAM)SIZE_RESTORED;
   m_pClockShow->PostMessage(WM_SIZE, wParam, lparam);


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Pu


 

The WM_SIZE message is sent to a window AFTER its size has changed.

WM_SIZE — не служит для того чтобы изменить размеры виндоу. Оно посылается окну после того как размеры изменили. И в качестве параметров передается состояние окна текущее.


Записан

Насколько я опытен? Достаточно, чтобы понимать, что дураков нельзя заставить думать по–другому, но недостаточно, чтобы отказаться от попыток это сделать.
(с) Артур Джонс

Pu


попробуй вот эту функцию АПИ —

The MoveWindow function changes the position and dimensions of the specified window. For a top-level window, the position and dimensions are relative to the upper-left corner of the screen. For a child window, they are relative to the upper-left corner of the parent window’s client area.

Syntax

BOOL MoveWindow(          HWND hWnd,
    int X,
    int Y,
    int nWidth,
    int nHeight,
    BOOL bRepaint
);
Parameters

hWnd
[in] Handle to the window.
X
[in] Specifies the new position of the left side of the window.
Y
[in] Specifies the new position of the top of the window.
nWidth
[in] Specifies the new width of the window.
nHeight
[in] Specifies the new height of the window.
bRepaint
[in] Specifies whether the window is to be repainted. If this parameter is TRUE, the window receives a message. If the parameter is FALSE, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of moving a child window.
Return Value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

« Последнее редактирование: 20-12-2007 17:57 от Алексей1153++ »
Записан

Насколько я опытен? Достаточно, чтобы понимать, что дураков нельзя заставить думать по–другому, но недостаточно, чтобы отказаться от попыток это сделать.
(с) Артур Джонс

Finch

Спокойный
Администратор

il
Offline Offline
Пол: Мужской

Пролетал мимо


Есть еше одна функция для этих целей

The SetWindowPos function changes the size, position, and Z order of a child, pop-up, or top-level window. Child, pop-up, and top-level windows are ordered according to their appearance on the screen. The topmost window receives the highest rank and is the first window in the Z order.

BOOL SetWindowPos(

    HWND hWnd,   // handle of window
    HWND hWndInsertAfter,   // placement-order handle
    int X,   // horizontal position
    int Y,   // vertical position
    int cx,   // width
    int cy,   // height
    UINT uFlags    // window-positioning flags
   );   

 Parameters

hWnd

Identifies the window.

hWndInsertAfter

Identifies the window to precede the positioned window in the Z order. This parameter must be a window handle or one of the following values:

Value   Meaning
HWND_BOTTOM   Places the window at the bottom of the Z order. If the hWnd parameter identifies a topmost window, the window loses its topmost status and is placed at the bottom of all other windows.
HWND_NOTOPMOST   Places the window above all non-topmost windows (that is, behind all topmost windows). This flag has no effect if the window is already a non-topmost window.
HWND_TOP   Places the window at the top of the Z order.
HWND_TOPMOST   Places the window above all non-topmost windows. The window maintains its topmost position even when it is deactivated.

 For more information about how this parameter is used, see the following Remarks section.

X

Specifies the new position of the left side of the window.

Y

Specifies the new position of the top of the window.

cx

Specifies the new width of the window, in pixels.

cy

Specifies the new height of the window, in pixels.

uFlags

Specifies the window sizing and positioning flags. This parameter can be a combination of the following values:

Value   Meaning
SWP_DRAWFRAME   Draws a frame (defined in the window’s class description) around the window.
SWP_FRAMECHANGED   Sends a WM_NCCALCSIZE message to the window, even if the window’s size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window’s size is being changed.
SWP_HIDEWINDOW   Hides the window.
SWP_NOACTIVATE   Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
SWP_NOCOPYBITS   Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
SWP_NOMOVE   Retains the current position (ignores the X and Y parameters).
SWP_NOOWNERZORDER   Does not change the owner window’s position in the Z order.
SWP_NOREDRAW   Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
SWP_NOREPOSITION   Same as the SWP_NOOWNERZORDER flag.
SWP_NOSENDCHANGING   Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
SWP_NOSIZE   Retains the current size (ignores the cx and cy parameters).
SWP_NOZORDER   Retains the current Z order (ignores the hWndInsertAfter parameter).
SWP_SHOWWINDOW   Displays the window.

 Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the SWP_SHOWWINDOW or SWP_HIDEWINDOW flag is set, the window cannot be moved or sized.
All coordinates for child windows are client coordinates (relative to the upper-left corner of the parent window’s client area).
A window can be made a topmost window either by setting the hWndInsertAfter parameter to HWND_TOPMOST and ensuring that the SWP_NOZORDER flag is not set, or by setting a window’s position in the Z order so that it is above any existing topmost windows. When a non-topmost window is made topmost, its owned windows are also made topmost. Its owners, however, are not changed.

If neither the SWP_NOACTIVATE nor SWP_NOZORDER flag is specified (that is, when the application requests that a window be simultaneously activated and its position in the Z order changed), the value specified in hWndInsertAfter is used only in the following circumstances:

·   Neither the HWND_TOPMOST nor HWND_NOTOPMOST flag is specified in hWndInsertAfter.
·   The window identified by hWnd is not the active window.

 An application cannot activate an inactive window without also bringing it to the top of the Z order. Applications can change an activated window’s position in the Z order without restrictions, or it can activate a window and then move it to the top of the topmost or non-topmost windows.
If a topmost window is repositioned to the bottom (HWND_BOTTOM) of the Z order or after any non-topmost window, it is no longer topmost. When a topmost window is made non-topmost, its owners and its owned windows are also made non-topmost windows.

A non-topmost window can own a topmost window, but the reverse cannot occur. Any window (for example, a dialog box) owned by a topmost window is itself made a topmost window, to ensure that all owned windows stay above their owner.
If an application is not in the foreground, and should be in the foreground, it must call the SetForegroundWindow function.

« Последнее редактирование: 20-12-2007 17:59 от Алексей1153++ »
Записан

Не будите спашяго дракона.
             Джаффар (Коша)

Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Pu,

Это идея, но возникает проблема — мне известны чистые размеры окна (без учета title bar). Для MoveWindow надо указать полные размеры… Т.е. как посчитать полную высоту (а точнее, как вычислить высоту title bar обычного диалога)?


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Finch

Спокойный
Администратор

il
Offline Offline
Пол: Мужской

Пролетал мимо


Есть функция GetSystemMetrics. Её вызовы с параметрами SM_CYCAPTION и SM_CYMENU, и SM_CXBORDER, и SM_CYBORDER тебе дадут размеры не клиентской области.

The GetSystemMetrics function retrieves various system metrics and system configuration settings.

System metrics are the dimensions (widths and heights) of Windows display elements. All dimensions retrieved by GetSystemMetrics are in pixels.

int GetSystemMetrics(

    int nIndex    // system metric or configuration setting to retrieve 
   );   

 Parameters

nIndex

Specifies the system metric or configuration setting to retrieve. All SM_CX* values are widths. All SM_CY* values are heights. The following values are defined: 

Value   Meaning
SM_ARRANGE   Flags specifying how the system arranged minimized windows. For more information about minimized windows, see the following Remarks section.
SM_CLEANBOOT   Value that specifies how the system was started:0  Normal boot1  Fail-safe boot2  Fail-safe with network bootFail-safe boot (also called SafeBoot) bypasses the user’s startup files.
SM_CMOUSEBUTTONS   Number of buttons on mouse, or zero if no mouse is installed.
SM_CXBORDER,
SM_CYBORDER   The width and height, in pixels, of a window border. This is equivalent to the SM_CXEDGE value for windows with the 3-D look.
SM_CXCURSOR,
SM_CYCURSOR   Width and height, in pixels, of a cursor. These are the cursor dimensions supported by the current display driver. The system cannot create cursors of other sizes.
SM_CXDLGFRAME,
SM_CYDLGFRAME   Same as SM_CXFIXEDFRAME and SM_CYFIXEDFRAME.
SM_CXDOUBLECLK,
SM_CYDOUBLECLK   Width and height, in pixels, of the rectangle around the location of a first click in a double-click sequence. The second click must occur within this rectangle for the system to consider the two clicks a double-click. (The two clicks must also occur within a specified time.)
SM_CXDRAG,
SM_CYDRAG   Width and height, in pixels, of a rectangle centered on a drag point to allow for limited movement of the mouse pointer before a drag operation begins. This allows the user to click and release the mouse button easily without unintentionally starting a drag operation.
SM_CXEDGE,
SM_CYEDGE   Dimensions, in pixels, of a 3-D border. These are the 3-D counterparts of SM_CXBORDER and SM_CYBORDER.
SM_CXFIXEDFRAME,
SM_CYFIXEDFRAME   Thickness, in pixels, of the frame around the perimeter of a window that has a caption but is not sizable. SM_CXFIXEDFRAME is the width of the horizontal border and SM_CYFIXEDFRAME is the height of the vertical border. Same as SM_CXDLGFRAME and SM_CYDLGFRAME.
SM_CXFRAME,
SM_CYFRAME   Same as SM_CXSIZEFRAME and SM_CYSIZEFRAME.
SM_CXFULLSCREEN, SM_CYFULLSCREEN   Width and height of the client area for a full-screen window. To get the coordinates of the portion of the screen not obscured by the tray, call the SystemParametersInfo function with the SPI_GETWORKAREA value.
SM_CXHSCROLL, SM_CYHSCROLL   Width, in pixels, of the arrow bitmap on a horizontal scroll bar; and height, in pixels, of a horizontal scroll bar.
SM_CXHTHUMB   Width, in pixels, of the thumb box in a horizontal scroll bar.
SM_CXICON,
SM_CYICON   The default width and height, in pixels, of an icon. These values are typically 32×32, but can vary depending on the installed display hardware.The LoadIcon function can only load icons of these dimensions.
SM_CXICONSPACING, SM_CYICONSPACING   Dimensions, in pixels, of a grid cell for items in large icon view. Each item fits into a rectangle of this size when arranged. These values are always greater than or equal to SM_CXICON and SM_CYICON.
SM_CXMAXIMIZED,
SM_CYMAXIMIZED   Default dimensions, in pixels, of a maximized top-level window.
SM_CXMAXTRACK,
SM_CYMAXTRACK   Default maximum dimensions, in pixels, of a window that has a caption and sizing borders. The user cannot drag the window frame to a size larger than these dimensions. A window can override these values by processing the WM_GETMINMAXINFO message.
SM_CXMENUCHECK,
SM_CYMENUCHECK   Dimensions, in pixels, of the default menu check-mark bitmap.
SM_CXMENUSIZE,
SM_CYMENUSIZE   Dimensions, in pixels, of menu bar buttons, such as multiple document (MIDI) child close.
SM_CXMIN,
SM_CYMIN   Minimum width and height, in pixels, of a window.
SM_CXMINIMIZED,
SM_CYMINIMIZED   Dimensions, in pixels, of a normal minimized window.
SM_CXMINSPACING
SM_CYMINSPACING   Dimensions, in pixels, of a grid cell for minimized windows. Each minimized window fits into a rectangle this size when arranged. These values are always greater than or equal to SM_CXMINIMIZED and SM_CYMINIMIZED.
SM_CXMINTRACK, SM_CYMINTRACK   Minimum tracking width and height, in pixels, of a window. The user cannot drag the window frame to a size smaller than these dimensions. A window can override these values by processing the WM_GETMINMAXINFO message.
SM_CXSCREEN,
SM_CYSCREEN   Width and height, in pixels, of the screen.
SM_CXSIZE,
SM_CYSIZE   Width and height, in pixels, of a button in a window’s caption or title bar.
SM_CXSIZEFRAME,
SM_CYSIZEFRAME   Thickness, in pixels, of the sizing border around the perimeter of a window that can be resized. SM_CXSIZEFRAME is the width of the horizontal border and SM_CYSIZEFRAME is the height of the vertical border. Same as SM_CXFRAME and SM_CYFRAME.
SM_CXSMICON,
SM_CYSMICON   Recommended dimensions, in pixels, of a small icon. Small icons typically appear in window captions and in small icon view.
SM_CXSMSIZE
SM_CYSMSIZE   Dimensions, in pixels, of small caption buttons.
SM_CXVSCROLL, SM_CYVSCROLL   Width, in pixels, of a vertical scroll bar; and height, in pixels, of the arrow bitmap on a vertical scroll bar.
SM_CYCAPTION   Height, in pixels, of normal caption area.
SM_CYKANJIWINDOW   For double-byte character set versions of Windows, height, in pixels, of the Kanji window at the bottom of the screen.
SM_CYMENU   Height, in pixels, of single-line menu bar.
SM_CYSMCAPTION   Height, in pixels, of a small caption.
SM_CYVTHUMB   Height , in pixels, of the thumb box in a vertical scroll bar.
SM_DBCSENABLED   TRUE or nonzero if the double-byte character set (DBCS) version of USER.EXE is installed; FALSE, or zero otherwise.
SM_DEBUG   TRUE or nonzero if the debugging version of USER.EXE is installed; FALSE, or zero, otherwise.
SM_MENUDROPALIGNMENT   TRUE, or nonzero if drop-down menus are right-aligned relative to the corresponding menu-bar item; FALSE, or zero if they are left-aligned.
SM_MIDEASTENABLED   TRUE if the system is enabled for Hebrew/Arabic languages.
SM_MOUSEPRESENT   TRUE or nonzero if a mouse is installed; FALSE, or zero, otherwise.
SM_MOUSEWHEELPRESENT   Windows NT only: TRUE or nonzero if a mouse with a wheel is installed; FALSE, or zero, otherwise.
SM_NETWORK   The least significant bit is set if a network is present; otherwise, it is cleared. The other bits are reserved for future use.
SM_PENWINDOWS   TRUE or nonzero if the Microsoft Windows for Pen computing extensions are installed; zero, or FALSE, otherwise.
SM_SECURE   TRUE if security is present, FALSE otherwise.
SM_SHOWSOUNDS   TRUE or nonzero if the user requires an application to present information visually in situations where it would otherwise present the information only in audible form; FALSE, or zero, otherwise.
SM_SLOWMACHINE   TRUE if the computer has a low-end (slow) processor, FALSE otherwise.
SM_SWAPBUTTON   TRUE or nonzero if the meanings of the left and right mouse buttons are swapped; FALSE, or zero, otherwise.

 Return Values

If the function succeeds, the return value is the requested system metric or configuration setting.
If the function fails, the return value is zero. GetLastError does not provide extended error information.

Remarks

System metrics may vary from display to display.
The SM_ARRANGE setting specifies how the system arranges minimized windows, and consists of a starting position and a direction. The starting position can be one of the following values.

Value   Meaning
ARW_BOTTOMLEFT   Start at lower-left corner of screen (default position).
ARW_BOTTOMRIGHT   Start at lower-right corner of screen. Equivalent to ARW_STARTRIGHT.
ARW_HIDE   Hide minimized windows by moving them off of the visible area of the screen.
ARW_TOPLEFT   Start at upper-left corner of screen. Equivalent to ARV_STARTTOP.
ARW_TOPRIGHT   Start at upper-right corner of screen. Equivalent to ARW_STARTTOP | SRW_STARTRIGHT.

 The direction in which to arrange can be one of the following values.

Value   Meaning
ARW_DOWN   Arrange vertically, top to bottom.
ARW_LEFT   Arrange horizontally, left to right.
ARW_RIGHT   Arrange horizontally, right to left.
ARW_UP   Arrange vertically, bottom to top.

« Последнее редактирование: 20-12-2007 18:01 от Алексей1153++ »
Записан

Не будите спашяго дракона.
             Джаффар (Коша)

Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Finch,

спасибочки! Ага


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Люди, опять караул, но с другой стороны : опять же есть MDI, т.е. MainFrame снаружи и View внутри. Сверху еще болтается немодальный диалог.
Мне надо при изменении размеров Frame-a (т.е. самого внешнего окна) изменять размеры View таким образом, чтобы окно View всегда было в пределах окна Frame. Попыталась сделать так :

void CMainFrame::OnSizing(UINT fwSide, LPRECT pRect)
{
CMDIFrameWnd::OnSizing(fwSide, pRect);

CRect rect1, rect2, rect3;
int nWidth1, nHight1, nWidth2, nHight2;

CTest_visuView* pView = NULL; 

getView(&pView);
if (pView)
{
// view
pView->GetClientRect(&rect1);
nWidth1 = rect1.Width();
nHight1 = rect1.Height();

// the main frame
this->GetClientRect(&rect2);
nWidth2 = rect2.Width();
nHight2 = rect2.Height();

if (nWidth1 < nWidth2 && nHight1 < nHight2)
{
return;
}

int nTBp = 0, nFS_Xp = 0, nFS_Yp = 0, nMS_Yp = 0;

// width of the title bar
nTBp = GetSystemMetrics(SM_CYCAPTION);
// Thickness, in pixels, of the sizing border around the perimeter of a
                                // window that can be resized.
nFS_Xp = GetSystemMetrics(SM_CXFRAME);
nFS_Yp = GetSystemMetrics(SM_CYFRAME);
// width of the menu bar
nMS_Yp = GetSystemMetrics(SM_CYMENUSIZE);

// resize the view
pView->SetWindowPos(&wndNoTopMost, rect1.left, rect1.top,
                                                nWidth2,nHight2,
SWP_DEFERERASE | SWP_DRAWFRAME |
                                       SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOMOVE);
//
// pView->MoveWindow(rect1.left, rect1.top, nWidth2 — 2 * nFS_Yp,
//   nHight2 — nTBp — nMS_Yp — 2 * nFS_Xp, TRUE);
pView->Invalidate();
Invalidate();
}
}

Не помогает ;-( Т.е. размеры окна View, судя по всему, меняются (видно из debuga), но чисто визуально не меняется ничего… А почему — не пойму, ведь Paint явно вызывается, во-первых, с помощью Invalidate, а во-вторых, флагом SWP_DRAWFRAME | SWP_FRAMECHANGED!


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Finch

Спокойный
Администратор

il
Offline Offline
Пол: Мужской

Пролетал мимо


  pView->SetWindowPos(&wndNoTopMost, rect1.left, rect1.top,
                                                nWidth2,nHight2,
SWP_DEFERERASE | SWP_DRAWFRAME |
                                       SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOMOVE);

Сразу предупрежу, Я не знаком с MFC.
Поэтому первое: Что есть такое wndNoTopMost и почему в функцию посылается его указатель. Если это подрузомевался параметр HWND hWndInsertAfter. То можно смело ставить NULL. Так как он должен игнорироваться согласно

SWP_NOZORDER   Retains the current Z order (ignores the hWndInsertAfter parameter).

Ну и второе: заместо rect1.left, rect1.top можно просто указать нули, так как эти параметры игнорируются

SWP_NOMOVE   Retains the current position (ignores the X and Y parameters).


Записан

Не будите спашяго дракона.
             Джаффар (Коша)

Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Finch,

это были остатки предыдущих попыток Ага Но проблемы это, к сожалению, не решает…


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Finch

Спокойный
Администратор

il
Offline Offline
Пол: Мужской

Пролетал мимо


Где то теряется посылка на обновление окна. Вот где. Нужно искать.
Есть пара коментариев:
1. Ты где либо запретила обновление окна.
2. У сообшения на обновление (WM_PAINT) есть два свойства.
   а) Это сообшение имеет очень низкий приоритет т.е. выполняется в самую последнюю очередь.
   б) Функции BeginPaint, EndPaint Которые обычно ставятся в обработчике сообшения WM_PAINT. Убивают все остальные сообшения WM_PAINT в очереди.
3. Посмотри в дебаге. Может быть твои попытки на изменение размеров провалились. Поля размеров остались прежними.

« Последнее редактирование: 17-03-2005 14:23 от Finch »
Записан

Не будите спашяго дракона.
             Джаффар (Коша)

Malaja

Команда клуба

de
Offline Offline
Пол: Женский


да я с самого начала посмотрела — поменялись, но не перерисовались ;-(


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Finch

Спокойный
Администратор

il
Offline Offline
Пол: Мужской

Пролетал мимо


В MFC не знаю, в Borland VCL сам факт изменения координат, уже вел к отрисовке, насколько я знаю.


Записан

Не будите спашяго дракона.
             Джаффар (Коша)

Finch

Спокойный
Администратор

il
Offline Offline
Пол: Мужской

Пролетал мимо


pView->Invalidate();
Invalidate();

Да кстати, Если pView является дочерним окном. То в принципе должно быть достаточно вызова на прорисовку родительского окна. И оно само автоматом даст команду на прорисовку всем дочерним окнам.


Записан

Не будите спашяго дракона.
             Джаффар (Коша)

Finch

Спокойный
Администратор

il
Offline Offline
Пол: Мужской

Пролетал мимо


Вот еше нашел

The WM_SIZE message is sent to a window after its size has changed.

WM_SIZE 
fwSizeType = wParam;      // resizing flag
nWidth = LOWORD(lParam);  // width of client area
nHeight = HIWORD(lParam); // height of client area

 Parameters

fwSizeType

Value of wParam. Specifies the type of resizing requested. This parameter can be one of the following values:

Value   Meaning
SIZE_MAXHIDE   Message is sent to all pop-up windows when some other window is maximized.
SIZE_MAXIMIZED   Window has been maximized.
SIZE_MAXSHOW   Message is sent to all pop-up windows when some other window has been restored to its former size.
SIZE_MINIMIZED   Window has been minimized.
SIZE_RESTORED   Window has been resized, but neither the SIZE_MINIMIZED nor SIZE_MAXIMIZED value applies.

 nWidth

Value of the low-order word of lParam. Specifies the new width of the client area.

nHeight

Value of the high-order word of lParam. Specifies the new height of the client area.

 Return Values

If an application processes this message, it should return zero.

Remarks

If the SetScrollPos or MoveWindow function is called for a child window as a result of the WM_SIZE message, the bRedraw parameter should be nonzero to cause the window to be repainted.
Although the width and height of a window are 32-bit values, the nWidth and nHeight parameters of the WM_SIZE message contain only the low-order 16 bits.

В нашем случае интересен выделенный абзац. Ненадо давать на прорисовку. Просто надо «bRedraw parameter should be nonzero»


Записан

Не будите спашяго дракона.
             Джаффар (Коша)

Hooter


void CMainFrame::OnSizing(UINT fwSide, LPRECT pRect)

А почему ты говоришь об обработке сообщения WM_SIZE, а используешь OnSizing?
OnSizing — это обработчик сообщения WM_SIZING в MFC

afx_msg void OnSizing(UINT nSide, LPRECT lpRect);

Обработчик WM_SIZE вообще другой вид имеет:

afx_msg void OnSize(UINT nType, int cx, int cy);

Имхо, ты просто не туда ткнула в ClassWizard’е  Улыбаюсь
Для решения твоей задачи тебе именно OnSize нужно использовать.
Вот пример кода из MSDN:

// Resize the list control contained in the view to
// fill the entire view when the view’s window is
// resized. CMyView is a CView derived class.
void CMyView::OnSize(UINT nType, int cx, int cy)
{
   CView::OnSize(nType, cx, cy);
   // Resize list to fill the whole view.
   m_List.MoveWindow (0, 0, cx, cy);
}

И работает без Paint или Invalidate.

« Последнее редактирование: 20-12-2007 18:05 от Алексей1153++ »
Записан
Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Finch, Hooter,

Я взяла WM_SIZING для более плавной перерисовки картинки (т.к. у меня еще сверху на всем этом немодальный диалог болтается, который должен всегда находиться в правом верхнем углу View).
Проблема заключается в том, что вне зависимости от обработчика (WM_SIZING или WM_SIZЕ) и функции ( MoveWindow(…, TRUE) или SetWindowPos ) размеры View меняются, но его перерисовка не происходит, т.е. визуально он остается все время одного размера.


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Hooter


Слушай, а зачем тебе вот это условие?

if (nWidth1 < nWidth2 && nHight1 < nHight2)
{
return;
}

Если у тебя View меньше, чем мейнфрейм или развернут на весь мейнфрейм, то условие всегда истинно. И код, который после условия — там, где ты пытаешься резмеры изменить — не выполняется.
Я вот сгенерил приложеньце и вставил твой код. Не работало. Убрал условие — все нормально стало. Здесь была моя ладья...
Или я что-то не понял в твоем коде?


Записан
Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Hooter,

согласна — условие можно убрать. Но и при этом перерисовка не происходит, т.е. при старте изначально View меньше MainFrame, если я тяну контур MainFrame, то ничего не меняется, хотя я и меняю размер View. Xотя я ожидаю, что при первом же изменении размера MainFrameразмер View будет изменен (согласно кода в обработчике OnSize()).


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Hooter


Тогда давай попробуем «плясать от печки», как говорится… Ага

Попробуй убрать всё в OnSizing, оставь только минимум кода.
И никаких относительных координат для View — при создании View сделай ему RECT{0, 0, 0, 0}, а в OnSizing задай размеры жестко.
Например, так:

void CMainFrame::OnSizing(UINT fwSide, LPRECT pRect)
{
    CMDIFrameWnd::OnSizing(fwSide, pRect);
    getView(&pView);
    if (pView)
    {
        pView->MoveWindow(0, 0, 1024, 1024);
    }
}

Посмотрим, что получится…


Записан
Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Hooter,

пробовала — не спасает ;-( Ситуация какая-то бредовая — если тянешь сам View, то resize срабатывает правильно и область перерисовывается. Если же тянешь MainFrame, то resize срабатывает правильно, но область View НЕ перерисовывается, а точнее перерисовывается только та область, которая не больше изначально при старте нарисованной. Если же новая область меньше изначально нарисованной, то только эта новая и перерисовывается, а остальное — нет…
А почему — не пойму!!! Ведь View получает свой OnSize!


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Джон

просто
Администратор

de
Offline Offline
Пол: Мужской


Malaja, я просмотрел топики и понял, что ничего не понял. Например как View может быть меньше MianFrame? Он вообще безразмерный — те заполняет всегда клиентскую область. Самое идеальное — если у тебя есть тестовый проектик — кинь на мыло.


Записан

Я вам что? Дурак? По выходным и праздникам на работе работать. По выходным и праздникам я работаю дома.
«Just because the language allows you to do something does not mean that it’s the correct thing to do.» Trey Nash
«Physics is like sex: sure, it may give some practical results, but that’s not why we do it.» Richard P. Feynman
«All science is either physics or stamp collecting.» Ernest Rutherford
«Wer will, findet Wege, wer nicht will, findet Gründe.»

Malaja

Команда клуба

de
Offline Offline
Пол: Женский


Dgon, spasibochki — uge skinula!


Записан

холоднокровней, Маня, Ви не на работе
—————————————
четкое определение сущности бытия:
— А мы в прошлом или в будущем?- спросила Алиса.
— Мы в жопе, — ответил кролик.
— А «жопа» — это настоящее? — спросила Алиса.
— А «жопа» — это у нас символ вечности.

Джон

просто
Администратор

de
Offline Offline
Пол: Мужской


В общем как я и думал… Речь идёт о MDI под изменением View наверно понимается изменение размеров CChildFrame.
В CMainFrame достаточно реагировать на WM_MOVE, обычно все ing-овые означают процесс, непосредственное действие (проще говоря начало действия, а не конечный результат)
WM_SIZE отлавливается в самом View, что она и сделала. Недостаёт только перемещений CChldFrame в пределах клиенской области CMainFrame.

Malaja, не удержался (может ещё кому-нить будет полезно):

bool CTest_visuView::moveDlg()
{
   CRect rect1, rect2;
   GetClientRect(&rect1);
   ClientToScreen(&rect1);
   if(rect1.Width()!=0 && rect1.Height()!=0)
   {
      m_pClockShow->GetWindowRect(&rect2);
      m_pClockShow->MoveWindow(rect1.right — rect2.Width(),
                         rect1.top, rect2.Width(), rect2.Height(), TRUE);
      return true;
   }
   return false;
}

В CChildFrame добавь:
1. #include «test_visuDoc.h»  в .срр
2. #include «test_visuView.h» в .срр
3.  ON_WM_MOVE()
4.

void CChildFrame::OnMove(int x, int y)
{
   CMDIChildWnd::OnMove(x, y);
   CView *pView = GetActiveView();
   if(pView)
   {
      ((CTest_visuView*)pView)->moveDlg();
   }
}

CMainFrame

1. OnSize можешь выкинуть — непонятно зачем оно вообще нужно?
2. OnMoving можешь выкинуть
3. View можно проще достать,вернее говоря твоя ф-я

CView* CTest_visuApp::getView()
{
   POSITION pos = this->GetFirstDocTemplatePosition();
   CDocTemplate* templ =  this->GetNextDocTemplate(pos);      
   POSITION posD = templ->GetFirstDocPosition();
   CDocument* docTmp = templ->GetNextDoc(posD);
   POSITION posV = docTmp->GetFirstViewPosition();
   CView* pView = docTmp->GetNextView(posV);
   return pView;
}

возвращает ТОЛЬКО первый View ТОЛЬКО первого документа, а если это не первый? тогда как? обычно для иттераций необходимо доп. условие поиска, тогда ты бежишь по всем въю всех документов пока не найдёшь нужный)

View активного документа (именно его ты перемещаешь и видишь)
CView *CMainFrame::GetActiveView()
{
   CMDIChildWnd *pChild = (CMDIChildWnd*)GetActiveFrame();
   if(pChild && pChild->IsKindOf(RUNTIME_CLASS(CChildFrame)))
   {
      return ((CChildFrame*)pChild)->GetActiveView();
   }
   return NULL;
}

4. Вместо ON_WM_MOVING используй ON_WM_MOVE

void CMainFrame::OnMove(int x, int y)
{
   CMDIFrameWnd::OnMove(x,y);
   CView *pView = GetActiveView();
   if (pView)
   {
      ((CTest_visuView*)pView)->moveDlg();
   }
}

5. Вместо (CTest_visuApp*)AfxGetApp() проще использовать theApp

В общем изменённый проект я тебе на мыло кину. Только я не уверен, что ты именно этого хотела — я имею ввиду привязку диалога к View. Но тут уже действует логика технического задания.

« Последнее редактирование: 22-03-2005 14:08 от Джон »
Записан

Я вам что? Дурак? По выходным и праздникам на работе работать. По выходным и праздникам я работаю дома.
«Just because the language allows you to do something does not mean that it’s the correct thing to do.» Trey Nash
«Physics is like sex: sure, it may give some practical results, but that’s not why we do it.» Richard P. Feynman
«All science is either physics or stamp collecting.» Ernest Rutherford
«Wer will, findet Wege, wer nicht will, findet Gründe.»

Понравилась статья? Поделить с друзьями:
  • Made up as a new word
  • Make a picture book in word
  • Loving your country word
  • Make a noun from the word given
  • Make a notebook in word